Data-Types in JavaScript - 045827
Data-Types in JavaScript - 045827
JavaScript includes data types similar to other programming languages like Java or C#. JavaScript is
dynamic and loosely typed language. It means you don't require to specify a type of a variable. A variable
in JavaScript can be assigned any type of value, as shown in the following example.
Example: Loosely Typed Variables
let myvariable = 1; // numeric value
myvariable = 'one'; // string value
myvariable = 1.1; // decimal value
myvariable = true; // Boolean value
myvariable = null; // null value
In the above example, different types of values are assigned to the same variable to demonstrate loosely
typed characteristics of JavaScript. Different values 1, 'one', 1.1, true are examples of different data
types.
JavaScript includes primitive and non-primitive data types as per latest ECMAScript 5.1.
String is a textual content wrapped inside ' ' or " " or ` ` (tick sign).
String
Example: 'Hello World!', "This is a string", etc.
Boolean Boolean is a logical data type that has only two values, true or false.
Undefined undefined is the default value of a variable that has not been assigned any
value.
Example: In the variable declaration, var str;, there is no value assigned to str.
So, the type of str can be check using typeof(str) which will return undefined.
1|Page
Structural Data Types
The structural data types contain some kind of structure with primitive data.
Data Type Description
Date Date object represents date & time including days, months, years,
hours, minutes, seconds and milliseconds.
Example: let today = new Date("25 July 2021");
2|Page
str[2] // l
str[3] // l
str[4] // o
str.length // 11
Since, string is character index, it can be accessed using for loop and for-of loop.
Example: Iterate String
var str = 'Hello World';
for(var i =0; i< str.length; i++)
console.log(str[i]);
for(var ch of str)
console.log(ch);
Concatenation
A string is immutable in JavaScript, it can be concatenated using plus (+) operator in JavaScript.
Example: String concatenation
var str = 'Hello ' + "World " + 'from ' + TICER ';
Include quotation marks inside string
Use quotation marks inside string value that does not match the quotation marks surrounding the string
value. For example, use single quotation marks if the whole string is enclosed with double quotation
marks and visa-versa.
Example: Quotes in string
var str1 = "This is 'simple' string";
var str2 = 'This is "simple" string';
If you want to include same quotes in a string value as surrounding quotes then use backward slash (\)
before quotation mark inside string value.
Example: Quotes in string
var str1 = "This is \"simple\" string";
var str2 = 'This is \'simple\' string';
String object
Above, we assigned a string literal to a variable. JavaScript allows you to create a String object using
the new keyword, as shown below.
Example: String object
var str1 = new String();
str1 = 'Hello World';
// or
3|Page
var str2 = new String('Hello World');
In the above example, JavaScript returns String object instead of primitive string type. It is recommended
to use primitive string instead of String object.
Caution:
Be careful while working with String object because comparison of string objects using == operat or
compares String objects and not the values. Consider the following example.
Example: String object comparison
var str1 = new String('Hello World');
var str2 = new String('Hello World');
var str3 = 'Hello World';
var str4 = str1;
str1 == str2; // false - because str1 and str2 are two different objects
str1 == str3; // true
str1 === str4; // true
typeof(str1); // object
typeof(str3); //string
JavaScript String Methods & Properties
JavaScript string (primitive or String object) includes default properties and methods which you can use
for different purposes.
String Properties
Property Description
String Methods
Method Description
charCodeAt(position) Returns a number indicating the Unicode value of the character at the
given position (in Number).
concat([string,,]) Joins specified string literal values (specify multiple strings separated
by comma) and returns a new string.
indexOf(SearchString, Position) Returns the index of first occurrence of specified String starting from
specified number index. Returns -1 if not found.
4|Page
Method Description
lastIndexOf(SearchString, Position)
Returns the last occurrence index of specified SearchString, starting
from specified position. Returns -1 if not found.
match(RegExp) Search a string for a match using specified regular expression. Returns
a matching array.
replace(searchValue, replaceValue)
Search specified string value and replace with specified replace Value
string and return new string. Regular expression can also be used as
searchValue.
slice(startNumber, endNumber) Extracts a section of a string based on specified starting and ending
index and returns a new string.
split(separatorString, limitNumber)
Splits a String into an array of strings by separating the string into
substrings based on specified separator. Regular expression can also
be used as separator.
substr(start, length) Returns the characters in a string from specified starting position
through the specified number of characters (length).
substring(start, end) Returns the characters in a string between start and end indexes.
Points to Remember:
1. JavaScript string must be enclosed in double or single quotes (" " or ' ').
2. String can be assigned to a variable using = operator.
3. Multiple strings can be concatenated using + operator.
4. A string can be treated as character array.
5. Use back slash (\) to include quotation marks inside string.
6. String objects can be created using new keyword. e.g. var str = new String();
5|Page
7. String methods are used to perform different task on strings.
JavaScript Numbers: Integer, Float, Binary, Exponential, Hexadecimal, Octal
The Number is a primitive data type used for positive or negative integer, float, binary , octal,
hexadecimal, and exponential values in JavaScript.
The Number type in JavaScript is double-precision 64 bit binary format like double in C# and Java. It
follows the international IEEE 754 standard.
The first character in a number type must be an integer value, and it must not be enclosed in quotation
marks. The following example shows the variables having different types of numbers in JavaScript.
Example: Numbers in JavaScript
var num1 = 100; // integer
var num2 = -100; //negative integer
var num3 = 10.52; // float
var num4 = -10.52; //negative float
var num5 = 0xfff; // hexadecimal
var num6 = 256e-5; // exponential
var num7 = 030; // octal
var num8 = 0b0010001; // binary
Integers
Numbers can be positive or negative integers. However, integers are floating-point values in JavaScript.
Integers value will be accurate up to 15 digits in JavaScript. Integers with 16 digits onwards will be
changed and rounded up or down; therefore, use BigInt for integers larger than 15 digits.
Example: Integers in JavaScript
//16 digit integer
var int1 = 1234567890123456; //accurate
//17 digit integer
var int2 = 12345678901234569; //will be 12345678901234568
//16 digit integer
var int3 = 9999999999999998; //will be 9999999999999998
//16 digit integer, last digit 9
var int4 = 9999999999999999; //will be 10000000000000000
BigInt
The BigInt type is a numeric primitive type that can store integers with arbitrary precision. Use the BigInt
for the large integers having more than 15 digits. Append n to the end of an integer to make it BigInt.
6|Page
Example: Integers in JavaScript
//16 digit integer
var int1 = 1234567890123459n; //will be 1234567890123459
//17 digit integer
var int2 = 12345678901234569n; //will be 12345678901234569
//20 digit integer
var int3 = 9999999999999999999n; //will be 9999999999999999999
Floating-point Numbers
The floating-point numbers in JavaScript can only keep 17 decimal places of precision; beyond that, the
value will be changed.
Example: Floating-point Numbers in JavaScript
//17 decimal places
var f1 = 123456789012345.9; //accurate
//18 decimal places
var f2 = 1234567890123456.9; //will be 1234567890123457
//19 decimal places
var f3 = 1234567890123456.79; //will be 1234567890123456.8
Arithmetic operations on floating-point numbers in JavaScript are not always accurate. For example:
Example: Arithmetic Operations on Floating-point Numbers
var f1 = 5.1 + 5.2; //will be 10.3
var f2 = 10.1 + 10.2; //will be 20.299999999999997
7|Page
var modulus = num % str; //returns 1
The + operator concatenates if any one value is a literal string.
Example: Arithmetic Operation on Number and String
var num = 5, str = "4";
var result = num + str; //returns "54"
8|Page
Compare Numbers
Be careful while comparing numbers using == or === operators. The == operator compares object
references and not the values whereas the === operator compare values. The following example
compares numbers created by different ways.
Example: Numbers Comparison
var num1 = new Number(100);
var num2 = Number('100');
var num3 = 100;
num1 == num2; // true
num1 === num2; // false
num2 == num3;//true
num2 === num3; // true
num1 == num3;//true
num1 === num3;//false
Number Properties
The Number type includes some default properties. JavaScript treats primitive values as objects, so all
the properties and methods are applicable to both literal numbers and number objects.
The following table lists all the properties of Number type.
Property Description
9|Page
Method Description
JavaScript Booleans
The boolean (not Boolean) is a primitive data type in JavaScript. It can have only two values: true or
false. It is useful in controlling program flow using conditional statements like if else, switch, while loop,
etc.
The followings are boolean variables.
Example: boolean Variables
var YES = true;
var NO = false;
The following example demonstrates how a boolean value controls the program flow using the if
condition.
Example: Boolean
10 | P a g e
var YES = true;
var NO = false;
if(YES)
{
alert("This code block will be executed");
}
if(NO)
{
alert("This code block will not be executed");
}
The comparison expressions return boolean values to indicate whether the comparison i s true or false.
For example, the following expressions return boolean values.
Example: boolean Expressions
var a = 10, b = 20;
11 | P a g e
var b1 = Boolean(''); // false
var b2 = Boolean(0); // false
var b3 = Boolean(null); // false
var a;
var b4 = Boolean(a); // false
The new operator with the Boolean() function returns a Boolean object.
Example: Boolean Object
var bool = new Boolean(true);
alert(bool); // true
Any boolean object, when passed in a conditional statement, will evaluate to true.
Example: Boolean Object in Condition
var bool = new Boolean(false);
if(bool){
alert('This will be executed.');
}
Boolean vs boolean
The new Boolean() will return a Boolean object, whereas it returns a boolean without the new keyword.
The boolean (lower case) is the primitive type, whereas Boolean (upper case) is an object in JavaScript.
Use the typeof operator to check the types.
Example: Boolean vs boolean
var b1 = new Boolean(true);
var b2 = true;
typeof b1; // object
typeof b2; // boolean
Boolean Methods
Primitive or Boolean object includes following methods.
Method Description
12 | P a g e
JavaScript Objects: Create Objects, Access Properties & Methods
Here you will learn objects, object literals, Object() constructor function, and access object in JavaScript.
You learned about primitive and structured data types in JavaScript. An object is a non-primitive,
structured data type in JavaScript. Objects are same as variables in JavaScript, the only difference is that
an object holds multiple values in terms of properties and methods.
In JavaScript, an object can be created in two ways: 1) using Object Literal/Initializer Syntax 2) using
the Object() Constructor function with the new keyword. Objects created using any of these methods
are the same.
The following example demonstrates creating objects using both ways.
Example: JavaScript Objects
var p1 = { name:"Steve" }; // object literal syntax
var p2 = new Object(); // Object() constructor function
p2.name = "Steve"; // property
Above, p1 and p2 are the names of objects. Objects can be declared same
as variables using var or let keywords. The p1 object is created using the object literal syntax (a short
form of creating objects) with a property named name. The p2 object is created by calling
the Object() constructor function with the new keyword. The p2.name = "Steve"; attach a
property name to p2 object with a string value "Steve".
13 | P a g e
// object with properties & method
var person = {
firstName: "James",
lastName: "Bond",
age: 15,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
Note that the whole key-value pair must be declared. Declaring only a key without a value is invalid, as
shown below.
Example: Wrong Syntax
var person = { firstName };
var person = { getFullName: };
Create Objects using Objects() Constructor
Another way of creating objects is using the Object() constructor function using the new keyword.
Properties and methods can be declared using the dot notation .property-name or using the square
brackets ["property-name"], as shown below.
Example: Create Object using Object() Constructor
var person = new Object();
// Attach properties and methods to person object
person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};
An object can have variables as properties or can have computed properties, as shown below.
Example: Variables as Object Properties
var firstName = "James";
var lastName = "Bond";
var person = { firstName, lastName }
14 | P a g e
Access JavaScript Object Properties & Methods
An object's properties can be accessed using the dot notation obj.property-name or the square
brackets obj["property-name"]. However, method can be invoked only using the dot notation with the
parenthesis, obj.method-name(), as shown below.
Example: Access JS Object
var person = {
firstName: "James",
lastName: "Bond",
age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
In the above example, the person.firstName access the firstName property of a person object.
The person["firstName"] is another way of accessing a property. An object's methods can be called using
() operator e.g. person.getFullName(). JavaScript engine will return the function definition if accessed
method without the parenthesis.
Accessing undeclared properties of an object will return undefined. If you are not sure whether an object
has a particular property or not, then use the hasOwnProperty() method before accessing them, as
shown below.
Example: hasOwnProperty()
var person = new Object();
person.firstName; // returns undefined
if(person.hasOwnProperty("firstName")){
person.firstName;
}
The properties and methods will be available only to an object where they are declared.
15 | P a g e
Example: Object Constructor
var p1 = new Object();
p1.firstName = "James";
p1.lastName = "Bond";
var p2 = new Object();
p2.firstName; // undefined
p2.lastName; // undefined
p3 = p1; // assigns object
p3.firstName; // James
p3.lastName; // Bond
p3.firstName = "Sachin"; // assigns new value
p3.lastName = "Tendulkar"; // assigns new value
Pass by Reference
Object in JavaScript passes by reference from one function to another.
Example: JS Object Passes by Reference
function changeFirstName(per)
{
per.firstName = "Steve";
}
var person = { firstName : "Bill" };
changeFirstName(person)
person.firstName; // returns Steve
16 | P a g e
Nested Objects
An object can be a property of another object. It is called a nested object.
Example: Nested JS Objects
var person = {
firstName: "James",
lastName: "Bond",
age: 25,
address: {
id: 1,
country:"UK"
}
};
person.address.country; // returns "UK"
Points to Remember:
1. JavaScript object is a standalone entity that holds multiple values in terms of properties and
methods.
2. Object property stores a literal value and method represents function.
3. An object can be created using object literal or object constructor syntax.
4. Object literal:
5. var person = {
6. firstName: "James",
7. lastName: "Bond",
8. age: 25,
9. getFullName: function () {
10. return this.firstName + ' ' + this.lastName
11. }
12. };
13. Object constructor:
14. var person = new Object();
15.
16. person.firstName = "James";
17. person["lastName"] = "Bond";
18. person.age = 25;
17 | P a g e
19. person.getFullName = function () {
20. return this.firstName + ' ' + this.lastName;
21. };
22. Object properties and methods can be accessed using dot notation or [ ] bracket.
23. An object is passed by reference from one function to another.
24. An object can include another object as a property.
18 | P a g e
monthIndex: An integer value to represent a month of a date. It starts with 0 for January till 11 for
December
day: An integer value to represent day of the month.
hours: An integer value to represent the hour of a day between 0 to 23.
minutes: An integer value to represent the minute of a time segment.
seconds: An integer value to represent the second of a time segment.
milliseconds: An integer value to represent the millisecond of a time segment. Specify numeric
milliseconds in the constructor to get the date and time elapsed from 1/1/1970.
In the following example, a date object is created by passing milliseconds in the Date() constructor
function. So date will be calculated based on milliseconds elapsed from 1/1/1970.
Example: Create Date by Specifying Milliseconds
var date1 = new Date(0); // Thu Jan 01 1970 05:30:00
var date2 = new Date(1000); // Thu Jan 01 1970 05:30:01
var date3 = new Date(5000); // Thu Jan 01 1970 05:30:05
The following example shows various formats of a date string that can be specified in
a Date() constructor.
Example: Create Date by Specifying Date String
var date1 = new Date("3 march 2015");
var date2 = new Date("3 February, 2015");
var date3 = new Date("3rd February, 2015"); // invalid date
var date4 = new Date("2015 3 February");
var date5 = new Date("3 2015 February ");
var date6 = new Date("February 3 2015");
var date7 = new Date("February 2015 3");
var date8 = new Date("2 3 2015");
var date9 = new Date("3 march 2015 20:21:44");
You can use any valid separator in the date string to differentiate date segments.
Example: Create Date using Different Date Separator
var date1 = new Date("February 2015-3");
var date2 = new Date("February-2015-3");
var date3 = new Date("February-2015-3");
19 | P a g e
var date5 = new Date("February,2015,3");
var date6 = new Date("February*2015,3");
var date7 = new Date("February$2015$3");
var date8 = new Date("3-2-2015"); // MM-dd-YYYY
var date9 = new Date("3/2/2015"); // MM-dd-YYYY
Specify seven numeric values to create a date object with the specified year, month and optionally date,
hours, minutes, seconds and milliseconds.
Example: Date
var date1 = new Date(2021, 2, 3); // Mon Feb 03 2021
var date2 = new Date(2021, 2, 3, 10); // Mon Feb 03 2021 10:00
var date3 = new Date(2021, 2, 3, 10, 30); // Mon Feb 03 2021 10:30
var date4 = new Date(2021, 2, 3, 10, 30, 50); // Mon Feb 03 2021 10:30:50
var date5 = new Date(2021, 2, 3, 10, 30, 50, 800); // Mon Feb 03 2021 10:30:50
Date Formats
JavaScript supports ISO 8601 date format by default - YYYY-MM-DDTHH:mm:ss.sssZ
Example: ISO Date Format
var dt = new Date('2015-02-10T10:12:50.5000z');
Convert Date Formats
Use different Date methods to convert a date from one format to another format, e.g., to Universal
Time, GMT, or local time format.
The following example demonstrates ToUTCString(), ToGMTString(), ToLocalDateString(),
and ToTimeString() methods to convert date into respective formats.
Example: Date Conversion in Different Formats
var date = new Date('2015-02-10T10:12:50.5000z');
date; 'Default format:'
date.toDateString();'Tue Feb 10 2015'
date.toLocaleDateString();'2/10/2015'
date.toGMTString(); 'GMT format'
date.toISOString(); '2015-02-10T10:12:50.500Z'
date.toLocaleString();'Local date Format '
date.toLocaleTimeString(); 'Locale time format '
date.toString('YYYY-MM-dd'); 'Tue Feb 10 2015 15:42:50'
date.toTimeString(); '15:42:50'
20 | P a g e
date.toUTCString(); 'UTC format '
To get date string in formats other than the ones listed above, you need to manually form the date string
using different date object methods. The following example converts a date string to DD -MM-YYYY
format.
Example: Get Date Segments
var date = new Date('4-1-2015'); // M-D-YYYY
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
var dateString = (d <= 9 ? '0' + d : d) + '-' + (m <= 9 ? '0' + m : m) + '-' + y;
getDay() Returns the day of the week (0 - 6) for the specified date.
21 | P a g e
Method Description
getTime() Returns the milliseconds as number since January 1, 1970, 00:00:00 UTC.
getTimezoneOffset() Returns the time zone offset in minutes for the current locale.
getUTCDate() Returns the day (1 - 31) of the month of the specified date as per UTC time
zone.
getUTCDay() Returns the day (0 - 6) of the week of the specified date as per UTC timezone.
getUTCFullYear() Returns the four digits year of the specified date as per UTC time zone.
getUTCHours() Returns the hours (0 - 23) of the specified date as per UTC time zone.
getUTCMilliseconds() Returns the milliseconds (0 - 999) of the specified date as per UTC time zone.
getUTCMinutes() Returns the minutes (0 - 59) of the specified date as per UTC time zone.
getUTCMonth() Returns the month (0 - 11) of the specified date as per UTC time zone.
getUTCSeconds() Returns the seconds (0 - 59) of the specified date as per UTC time zone.
getYear() Returns the no of years of the specified date since 1990. This method is
Deprecated
The following table lists all the set methods of Date object.
Method Description
setFullYear() Sets the four-digit full year as number in the date object. Optionally set month
and date.
setHours() Sets the hours as number in the date object. Optionally set minutes, seconds
and milliseconds.
setMinutes() Sets the minutes as number in the date object. Optionally set seconds &
milliseconds.
setMonth() Sets the month as number in the date object. Optionally set date.
setSeconds() Sets the seconds as number in the date object. Optionally set milliseconds.
setTime() Sets the time as number in the Date object since January 1, 1970, 00:00:00
UTC.
setUTCDate() Sets the day in the date object as per UTC time zone.
setUTCFullYear() Sets the full year in the date object as per UTC time zone
22 | P a g e
Method Description
setUTCHours() Sets the hour in the date object as per UTC time zone
setUTCMilliseconds() Sets the milliseconds in the date object as per UTC time zone
setUTCMinutes() Sets the minutes in the date object as per UTC time zone
setUTCMonth() Sets the month in the date object as per UTC time zone
setUTCSeconds() Sets the seconds in the date object as per UTC time zone
setYear() Sets the year in the date object. This method is Deprecated
toDateString() Returns the date segment from the specified date, excludes time.
toLocaleDateString() Returns the date segment of the specified date using the current locale.
toTimeString() Returns the time segment as a string from the specified date object.
JavaScript Array
We have learned that a variable can hold only one value, for example var i = 1, we can assign only one
literal value to i. We cannot assign multiple literal values to a variable i. To overcome this problem,
JavaScript provides an array.
An array is a special type of variable, which can store multiple values using special syntax. Every value is
associated with numeric index starting with 0. The following figure illustrates how an array stores values.
JavaScript Array
Array Initialization
An array in JavaScript can be defined and initialized in two ways, array literal and Array constructor
syntax.
23 | P a g e
Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma and enclosed in square
brackets.:
var <array-name> = [element0, element1, element2,... elementN];
The following example shows how to define and initialize an array using array literal syntax.
Example: Declare and Initialize JS Array
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
var decimalArray = [1.1, 1.2, 1.3];
var booleanArray = [true, false, false, true];
var mixedArray = [1, "two", "three", 4];
JavaScript array can store multiple element of different data types. It is not required to store value of
same data type in an array.
Array Constructor
You can initialize an array with Array constructor syntax using new keyword.
The Array constructor has following three forms.ntax:
var arrayName = new Array();
var arrayName = new Array(Number length);
var arrayName = new Array(element1, element2, element3,... elementN);
As you can see in the above syntax, an array can be initialized using new keyword, in the same way as
an object.
The following example shows how to define an array using Array constructor syntax.
Example: Array Constructor Syntax
var stringArray = new Array();
stringArray[0] = "one";
stringArray[1] = "two";
stringArray[2] = "three";
stringArray[3] = "four";
var numericArray = new Array(3);
numericArray[0] = 1;
numericArray[1] = 2;
numericArray[2] = 3;
var mixedArray = new Array(1, "two", 3, "four");
24 | P a g e
Please note that array can only have numeric index (key). Index cannot be of string or any other data
type. The following syntax is incorrect.
Example: Incorrect Array Index
var stringArray = new Array();
stringArray["one"] = "one";
stringArray["two"] = "two";
stringArray["three"] = "three";
stringArray["four"] = "four";
Accessing Array Elements
An array elements (values) can be accessed using index (key). Specify an index in square bracket with
array name to access the element at particular index. Please note that index of an array starts from zero
in JavaScript.
Example: Access Array Elements
var stringArray = new Array("one", "two", "three", "four");
stringArray[0]; // returns "one"
stringArray[1]; // returns "two"
stringArray[2]; // returns "three"
stringArray[3]; // returns "four"
var numericArray = [1, 2, 3, 4];
numericArray[0]; // returns 1
numericArray[1]; // returns 2
numericArray[2]; // returns 3
numericArray[3]; // returns 4
Array Properties
Array includes "length" property which returns number of elements in the array.
Use for loop to access all the elements of an array using length property.
Example: Access Array using for Loop
var stringArray = new Array("one", "two", "three", "four");
for (var i = 0; i < stringArray.length ; i++)
{
stringArray[i];
}
25 | P a g e
Points to Remember:
1. An array is a special type of variable that stores multiple values using a special syntax.
2. An array can be created using array literal or Array constructor syntax.
3. Array literal syntax: var stringArray = ["one", "two", "three"];
4. Array constructor syntax:var numericArray = new Array(3);
5. A single array can store values of different data types.
6. An array elements (values) can be accessed using zero based index (key). e.g. array[0].
7. An array index must be numeric.
8. Array includes length property and various methods to operate on array objects.
concat() Returns new array by combining values of an array that is specified as parameter with
existing array values.
every() Returns true or false if every element in the specified array satisfies a condition specified
in the callback function. Returns false even if single element does not satisfy the
condition.
filter() Returns a new array with all the elements that satisfy a condition specified in the
callback function.
indexOf() Returns the index of the first occurrence of the specified element in the array, or -1 if it
is not found.
join() Returns string of all the elements separated by the specified separator
lastIndexOf() Returns the index of the last occurrence of the specified element in the array, or -1 if it
is not found.
map() Creates a new array with the results of calling a provided function on every element in
this array.
pop() Removes the last element from an array and returns that element.
26 | P a g e
Method Description
push() Adds one or more elements at the end of an array and returns the new length of the
array.
reduce() Pass two elements simultaneously in the callback function (till it reaches the last
element) and returns a single value.
reduceRight() Pass two elements simultaneously in the callback function from right-to-left (till it
reaches the last element) and returns a single value.
reverse() Reverses the elements of an array. Element at last index will be first and element at 0
index will be last.
shift() Removes the first element from an array and returns that element.
some() Returns true if at least one element in this array satisfies the condition in the callback
function.
unshift() Adds one or more elements to the front of an array and returns the new length of the
array.
27 | P a g e
null is of object type e.g. typeof null will return "object"
If you try to find DOM element using document.getElelementByID for example, and if element is found
then it will return null. So it is recommended to check for null before doing something with that element.
Example: null
var saveButton = document.getElementById("save");
if (saveButton !== null)
saveButton.submit();
A null value evaluates to false in conditional expression. So you don't have to use comparison operators
like === or !== to check for null values.
Example: null in conditional expression
var myVar = null;
if (myVar)
alert("myVar is not null');
else
alert("myVar is null" );
undefined
Undefined is also a primitive value in JavaScript. A variable or an object has an undefined value when no
value is assigned before using it. So you can say that undefined means lack of value or unknown value.
Example: undefined
var myVar;
alert(myVar); // undefined
28 | P a g e
var result = Sum(5, 5);
alert(result);// undefined
In the above example, a function Sum does not return any result but still we try to assign its resulted
value to a variable. So in this case, result will be undefined.
If you pass less arguments in function call then, that parameter will have undefined value.
Example: undefined
function Sum(val1, val2)
{
return val1 + val2; // val2 is undefined
}
Sum(5);
An undefined evaluates to false when used in conditional expression.
Example: undefined in Conditional Expression
var myVar;
if (myVar)
alert("myVar evaluates to true");
else
alert("myVar evaluates to false");
null and undefined is one of the main reasons to produce a runtime error in the JavaScript application.
This happens if you don't check the value of unknown return variables before using it. If you are not sure
that a variable will always have some value, the best practice is to check the value of variables for null
or undefined before using them.
Points to Remember:
1. null and undefined are primitive values in JavaScript.
2. A null value means absence.
3. An undefined value means lacks of value.
4. A null or undefined value evalutes to false in conditional expression.
29 | P a g e