0% found this document useful (0 votes)
6K views

Data-Types in JavaScript - 045827

JavaScript includes primitive data types like string, number, boolean, null, undefined and object. Strings can be created using single, double or backtick quotes. Strings are immutable and can be concatenated using + operator. Common string methods include charAt, concat, indexOf, replace and more to manipulate strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6K views

Data-Types in JavaScript - 045827

JavaScript includes primitive data types like string, number, boolean, null, undefined and object. Strings can be created using single, double or backtick quotes. Strings are immutable and can be concatenated using + operator. Common string methods include charAt, concat, indexOf, replace and more to manipulate strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

JavaScript Data Types

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.

Primitive Data Types


The primitive data types are the lowest level of the data value in JavaScript. The typeof operator can be
used with primitive data types to know the type of a value.
The followings are primitive data types in JavaScript:
Data Type Description

String is a textual content wrapped inside ' ' or " " or ` ` (tick sign).
String
Example: 'Hello World!', "This is a string", etc.

Number is a numeric value.


Number
Example: 100, 4521983, etc.

BigInt is a numeric value in the arbitrary precision format.


BigInt
Example: 453889879865131n, 200n, etc.

Boolean Boolean is a logical data type that has only two values, true or false.

A null value denotes an absense of value.


Null
Example: let str = null;

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

Object An object holds multiple values in terms of properties and methods.


Example:
let person = {
firstName: "James",
lastName: "Bond",
age: 15
};

Date Date object represents date & time including days, months, years,
hours, minutes, seconds and milliseconds.
Example: let today = new Date("25 July 2021");

Array An array stores multiple values using special syntax.


Example: let nums = [1, 2, 3, 4];

JavaScript Strings: Create Strings, Concate, Compare


Here you will learn what string is, how to create, compare and concatenate strings in JavaScript.
String is a primitive data type in JavaScript. A string is textual content. It must be enclosed in single or
double quotation marks.
Example: String literal
"Hello World"
'Hello World'
String value can be assigned to a variable using equal to (=) operator.
Example: String literal assigned to a variable
var str1 = "Hello World";

var str2 = 'Hello World';


A string can also be treated like zero index based character array.
Example: String as array
var str = 'Hello World';
str[0] // H
str[1] // e

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

length Returns the length of the string.

String Methods
Method Description

charAt(position) Returns the character at the specified position (in Number).

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.

localeCompare(string,position) Compares two strings in the current locale.

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.

search(RegExp) Search for a match based on specified regular expression.

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.

toLocaleLowerCase() Converts a string to lower case according to current locale.

toLocaleUpperCase() Converts a sting to upper case according to current locale.

toLowerCase() Returns lower case string value.

toString() Returns the value of String object.

toUpperCase() Returns upper case string value.

valueOf() Returns the primitive value of the specified string object.

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

var f3 = (10.1*100 + 10.2*100)/100; //instead of 10.1 + 10.2


Arithmetic operation (except addition) of the numeric string will result in a number, as shown below.
Example: Arithmetic Operation of Numeric Strings
var numStr1 = "5", numStr2 = "4";
var multiplication = numStr1 * numStr2; //returns20
var division = numStr1 / numStr2; //returns 1.25
var modulus = numStr1 % numStr2; //returns 1
Even if one of the values is a number, the result would be the same.
Example: Arithmetic Operation on Number and String
var num = 5, str = "4";
var multiplication = num * str; //returns 20
var division = num / str; //returns 1.25

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"

Binary, Octal, Hexadecimal, Exponential


The binary numbers must start with 0b or 0B followed by 0 or 1.
The octal numbers must start with zero and the lower or upper letter 'O', 0o or 0O.
The Hexadecimal numbers must start with zero and the lower or upper letter 'X', 0x or 0X.
The exponential numbers should follow the beN format where b is a base integer or float number
followed by e char, and N is an exponential power number.
Example: Binary, Ocal, Hexadecimal, Exponential Numbers
var b = 0b100; // binary
var oct = 0o544; // octal
var hex = 0x123456789ABCDEF; // hexadecimal
var exp = 256e-5; // exponential
Number() Function in JavaScript
The Number() is a constructor function in JavaScript that converts values of other types to numbers.
Example: Number() Function
var i = Number('100');
var f = Number('10.5');
var b = Number('0b100');
typeof(i); // returns number
typeof(f); // returns number
typeof(b); // returns number
By using the new operator with the Number() function will return an object which contains constants
and methods for working with numbers.
Example: Number Object
var i = new Number('100');
var f = new Number('10.5');
var b = new Number('0b100');
typeof(i); // returns object
typeof(f); // returns object
typeof(b); // returns object

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

MAX_VALUE Returns the maximum number value supported in JavaScript

MIN_VALUE Returns the smallest number value supported in JavaScript

NEGATIVE_INFINITY Returns negative infinity (-Infinity)

NaN Represents a value that is not a number.

POSITIVE_INFINITY Represents positive infinity (Infinity).


Example: Number properties
Number.MAX_VALUE; //1.7976931348623157e+308
Number.MIN_VALUE; //5e-324
Number.NEGATIVE_INFINITY; //-Infinity
Number.POSITIVE_INFINITY; //Infinity
Number.NaN;//NaN
Number Methods
The following table lists all the methods of Number type

9|Page
Method Description

toExponential(fractionDigits) Returns exponential value as a string.


Example:
var num = 100; num.toExponential(2); // returns '1.00e+2'

toFixed(fractionDigits) Returns string of decimal value of a number based on specified


fractionDigits
Example:
var num = 100; num.toFixed(2); // returns '100.00'

toLocaleString() Returns a number as a string value according to a browser's locale


settings.
Example:
var num = 100; num.toLocaleString(); // returns '100'

toPrecision(precisionNumber) Returns number as a string with specified total digits.


Example:
var num = 100; num.toPrecision(4); // returns '100.0'

toString() Returns the string representation of the number value.


Example:
var num = 100; num.toString(); // returns '100'

valueOf() Returns the value of Number object.


Example: var num = new Number(100); num.valueOf(); // returns
'100'

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;

var result = 1 > 2; // false


result = a < b; // true
result = a > b; // false
result = a + 20 > b + 5; // true
Boolean Function
JavaScript provides the Boolean() function that converts other types to a boolean type. The value
specified as the first parameter will be converted to a boolean value. The Boolean() will return true for
any non-empty, non-zero, object, or array.
Example: Boolean() Function
var a = 10, b = 20;
var b1 = Boolean('Hello'); // true
var b2 = Boolean('h'); // true
var b3 = Boolean(10); // true
var b4 = Boolean([]); // true
var b5 = Boolean(a + b); // true
If the first parameter is 0, -0, null, false, NaN, undefined, '' (empty string), or no parameter passed then
the Boolean() function returns false.
Example: Boolean() Function

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

toLocaleString() Returns string of boolean value in local browser environment.


Example: var result = (1 > 2); result.toLocaleString(); // returns "false"

toString() Returns a string of Boolean.


Example: var result = (1 > 2); result.toString(); // returns "false"

valueOf() Returns the value of the Boolean object.


Example: var result = (1 > 2); result.valueOf(); // returns false

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".

Create Object using Object Literal Syntax


The object literal is a short form of creating an object. Define an object in the { } brackets with key:value
pairs separated by a comma. The key would be the name of the property and the value will be a literal
value or a function.
var <object-name> = { key1: value1, key2: value2,...};
The following example demonstrates objects created using object literal syntax.
Example: Object Literal Syntax
var emptyObject = {}; // object with no properties or methods
var person = { firstName: "John" }; // object with single property
// object with single method
var message = {
showMessage: function (val) {
alert(val);
}
};

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
}
};

person.firstName; // returns James


person.lastName; // returns Bond
person["firstName"];// returns James
person["lastName"];// returns Bond
person.getFullName(); // calling getFullName function

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

Enumerate Object's Properties


Use the for in loop to enumerate an object, as shown below.
Example: Access Object Keys
var person = new Object();
person.firstName = "James";
person.lastName = "Bond";
for(var prop in person){
alert(prop); // access property name
alert(person[prop]); // access property 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.

JavaScript Date: Create, Convert, Compare Dates in JavaScript


JavaScript provides Date object to work with date & time, including days, months, years, hours, minutes,
seconds, and milliseconds.
Use the Date() function to get the string representation of the current date and time in JavaScript. Use
the new keyword in JavaScript to get the Date object.
Example: Date In JavaScript
Date(); //Returns current date and time string
//or
var currentDate = new Date(); //returns date object of current date and time
Create a date object by specifying different parameters in the Date() constructor function.
Date() Syntax
new Date()
new Date(value)
new Date(dateString)
new Date(year, monthIndex)
new Date(year, monthIndex, day)
new Date(year, monthIndex, day, hours)
new Date(year, monthIndex, day, hours, minutes)
new Date(year, monthIndex, day, hours, minutes, seconds)
new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
Parameters:
 No Parameters: A date object will be set to the current date & time if no parameter is specified in the
constructor.
 value: An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC.
 dateString: A string value that will be parsed using Date.parse() method.
 year: An integer value to represent a year of a date. Numbers from 0 to 99 map to the years 1900 to
1999. All others are actual years.

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");

var date4 = 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;

Compare Dates in JavaScript


Use comparison operators to compare two date objects.
Example: Date Comparison
var date1 = new Date('4-1-2015');
var date2 = new Date('4-2-2015');
if (date1 > date2)
alert(date1 + ' is greater than ' + date2);
else (date1 < date2 )
alert(date1 + ' is less than ' + date2);

Date Methods Reference


The following table lists all the get methods of Date object.
Method Description

getDate() Returns numeric day (1 - 31) of the specified date.

getDay() Returns the day of the week (0 - 6) for the specified date.

getFullYear() Returns four digit year of the specified date.

getHours() Returns the hour (0 - 23) in the specified date.

getMilliseconds() Returns the milliseconds (0 - 999) in the specified date.

getMinutes() Returns the minutes (0 - 59) in the specified date.

getMonth() Returns the month (0 - 11) in the specified date.

21 | P a g e
Method Description

getSeconds() Returns the seconds (0 - 59) in the specified date.

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

setDate() Sets the day as number in the date object.

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.

setMilliseconds() Sets the milliseconds as number in the date object.

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.

toGMTString() Returns a date string in GMT time zone.

toLocaleDateString() Returns the date segment of the specified date using the current locale.

toLocaleFormat() Returns a date string in default format.

toLocaleString() Returns a date string using a current locale format.

toLocaleTimeString() Returns the time segment of the specified Date as a string.

toString() Returns a string for the specified Date object.

toTimeString() Returns the time segment as a string from the specified date object.

toUTCString() Returns a string as per UTC time zone.

valueOf() Returns the primitive value of a 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.

Array Methods Reference


The following table lists all the Array methods.
Method Description

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.

forEach() Executes a callback function for each elements of an array.

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.

slice() Returns a new array with specified start to end elements.

some() Returns true if at least one element in this array satisfies the condition in the callback
function.

sort() Sorts the elements of an array.

splice() Adds and/or removes elements from an array.

toString() Returns a string representing the array and its elements.

unshift() Adds one or more elements to the front of an array and returns the new length of the
array.

null and undefined in JavaScript


As we have seen in the variable section that we can assign any primitive or non-primitive type of value
to a variable. JavaScript includes two additional primitive type values - null and undefined, that can be
assigned to a variable that has special meaning.
null
You can assign null to a variable to denote that currently that variable does not have any value but it
will have later on. A null means absence of a value.
Example: null
var myVar = null;
alert(myVar); // null
In the above example, null is assigned to a variable myVar. It means we have defined a variable but have
not assigned any value yet, so value is absence.

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

undefined is a token. typeof undefined will return undefined not an object.


In the above example, we have not assigned any value to a variable named 'myVar'. A variable 'myVar'
lacks a value. So it is undefined.
You will get undefined value when you call a non-existent property or method of an object.
Example: undefined
function Sum(val1, val2)
{
var result = val1 + val2;
}

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

You might also like