You are on page 1of 48

JavaScript

Table of Contents
1 Prerequisite: ................................................................................................................................. 6
2 What is JavaScript? ...................................................................................................................... 6
3 Main uses of JavaScript? .............................................................................................................. 6
4 Where to code?............................................................................................................................ 6
4.1 JavaScript in head section ..................................................................................................... 7
4.2 JavaScript in body section ..................................................................................................... 7
4.3 External JavaScript ................................................................................................................ 7
5 Try out this ................................................................................................................................... 8
6 JavaScript Basics ........................................................................................................................... 8
6.1 Javascript statements ........................................................................................................... 8
6.2 Events .................................................................................................................................. 10
7 Comments .................................................................................................................................. 10
8 Variables and types .................................................................................................................... 11
8.1 Declarations ........................................................................................................................ 11
8.2 Declaring Variables ............................................................................................................. 11
8.3 Variable Scope .................................................................................................................... 11
8.4 Variable Hoisting ................................................................................................................. 12
8.5 Constants ............................................................................................................................ 13
8.6 Data types. .......................................................................................................................... 13

8.7 Data type conversion .......................................................................................................... 13


9 Strings......................................................................................................................................... 14
9.1 String methods .................................................................................................................... 14
9.1.1 The String length method: ........................................................................................... 14
9.1.2 The indexOf() method:................................................................................................. 15
9.1.3 The lastIndexOf() method: ........................................................................................... 15
9.1.4 The search method: ..................................................................................................... 15
9.1.5 The replace method: .................................................................................................... 15
9.1.6 The toUpperCase() method and toLowerCase() method: ........................................... 16
9.1.7 The concat() method: .................................................................................................. 16
10 Array ......................................................................................................................................... 16
10.1 Creating an array............................................................................................................... 17
10.2 Displaying array................................................................................................................. 17
10.3 Array Methods .................................................................................................................. 17
10.3.1 The concat() method: ................................................................................................ 17
10.3.2 The join() method: ..................................................................................................... 18
10.3.3 The push() method: ................................................................................................... 18
10.3.4 The pop() method: ..................................................................................................... 18
10.3.5 The shift() method: .................................................................................................... 19
10.3.6 The unshift() method: ................................................................................................ 19
10.3.7 The reverse() method: ............................................................................................... 19
10.3.8 The sort() method: ..................................................................................................... 20
10.3.9 The slice() method: .................................................................................................... 20
11 Object ....................................................................................................................................... 20

12 Control flow statements .......................................................................................................... 21


12.1 Block Statements .............................................................................................................. 21
12.2 Conditional statements..................................................................................................... 22
12.2.1 If..else statement : ..................................................................................................... 22
12.2.2 switch Statement : ..................................................................................................... 23
12.3 Exception handling statements ........................................................................................ 25
13 Loops and iteration .................................................................................................................. 26
13.1 for statement .................................................................................................................... 26
13.2 while statement ................................................................................................................ 27
13.3 do...while statement ......................................................................................................... 28
13.4 break statement................................................................................................................ 28
13.5 continue statement .......................................................................................................... 29
13.6 for...in statement .............................................................................................................. 29
14 Functions .................................................................................................................................. 30
14.1 Function declaration ......................................................................................................... 30
14.2 Calling function ................................................................................................................. 31
14.3 Function return ................................................................................................................. 31
14.4 Function Scope .................................................................................................................. 31
14.5 Nested functions ............................................................................................................... 32
15 Operators ................................................................................................................................. 32
15.1 Assignment operators ....................................................................................................... 33
15.2 Comparison operators ...................................................................................................... 33
15.3 Arithmetic operators ........................................................................................................ 34
15.4 Bitwise operators .............................................................................................................. 35

15.5 Logical operators............................................................................................................... 35


15.6 String operators ................................................................................................................ 36
15.7 Conditional operator......................................................................................................... 36
15.8 Unary operator ................................................................................................................. 37
15.9 Relational operator ........................................................................................................... 37
16 Numbers................................................................................................................................... 38
16.1 Number systems ............................................................................................................... 38
16.1.1 Decimal numbers ....................................................................................................... 38
16.1.2 Binary numbers .......................................................................................................... 38
16.1.3 Hexadecimal numbers ............................................................................................... 38
16.1.4 NaN ............................................................................................................................ 39
16.2 Number object .................................................................................................................. 39
16.2.1 Properties of numbers ............................................................................................... 39
16.2.2 Methods of Numbers ................................................................................................. 40
16.3 Math object ....................................................................................................................... 41
16.3.1 Methods of Math object ............................................................................................ 41
17 Dates ........................................................................................................................................ 42
17.1 Date object ........................................................................................................................ 42
17.2 Date object methods ........................................................................................................ 43
17.2.1 Set methods ............................................................................................................... 43
17.2.2 Get methods .............................................................................................................. 43
17.2.3 Parsing method .......................................................................................................... 44
18 Regular expressions ................................................................................................................. 45
18.1 RegExp with String methods ............................................................................................. 45

18.2 Modifiers ........................................................................................................................... 46


18.3 Patterns ............................................................................................................................. 46
18.3.1 Brackets...................................................................................................................... 46
18.3.2 Quantifiers ................................................................................................................. 47
18.3.3 Metacharacters .......................................................................................................... 47
18.4 RegExp Object ................................................................................................................... 48
18.4.1 test() method: ............................................................................................................ 48
18.4.2 exec() method: ........................................................................................................... 48

1 Prerequisite:
Before starting with JavaScript, you must have good knowledge of HyperText Markup
Language(HTML).

2 What is JavaScript?
JavaScript is an object-oriented scripting language. It is small and lightweight. JavaScript is a
cross-platform language. JavaScript contains a standard library of objects, such as Array, Date,
and Math, and a core set of language elements such as operators, control structures, and
statements.

3 Main uses of JavaScript?


JavaScript is used to change HTML and CSS contents dynamically, i.e. it used for making
dynamic web pages.

4 Where to code?
The script tag is used for adding javascript to your HTML document.
JavaScript code can be placed in the head or body section or we can even create an external
javascript file with (.js) extension.

4.1 JavaScript in head section


Inside head section create a script tag. Inside script write your javascript code.

<head>
<script>
...JavaScript code...
<script>
</head>

4.2 JavaScript in body section


Inside body section create a script tag. Inside script write your javascript code.
<body>
<script>
...JavaScript code...
<script>
</body>

4.3 External JavaScript


Create a file with .js extension. This will be your external javascript file. Now write your
javascript code inside this file. For importing this file use the script tag with src=Your file
name.
<script src="FileName.js" />

5 Try out this


<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function greet(Name) {
alert("Hello " + Name);
}

greet("World");
</script>
</body>
</html>

6 JavaScript Basics
Most of javascript syntax are similar to java.
JavaScript is case-sensitive and uses the Unicode character set.
A javascript code consist of statements which end with semicolon(;).

6.1 Javascript statements


JavaScript statements can be used to make changes in a static HTML webpage using JavaScript.
One such often used statement is given below.
document.getElementById( Id_of_element )

Document object is used to access and manipulate HTML.

Try out this example


<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Click the button.</p>
<button onclick="sayHello()">Valar Morghulis!</button>
<p id="demo"></p>
<script>
function sayHello() {
document.getElementById("demo").innerHTML = "Valar Dohaeris!";
}
</script>
</body>
</html>

In this example, the button have been assigned the function sayHello(). When the button is
clicked, the function sayHello() fetches the element with id = demo and copies the text Valar
Dohaeris inside that element(.innerHTML copies the text inside that <p> tag). This is a basic
application of JavaScript. I have explained every part of it in the later part of this module so
dont worry, youll get the hang of it !

6.2 Events
There are a list of events which you can use in JavaScript.
Event

Description

onclick

When this element is clicked, execute the


specified action.

onchange

When this element is changed, execute the


specified action.

onmouseover

When the user moves the mouse over this


element, execute the specified action.

onmouseout

When mouse leaves this element, execute


the specified action.

onkeydown

When the user pushes a keyboard key,


execute the specified action.

onload

When the page is completely loaded, execute


the specified action.

7 Comments
Comments in javascript are same as that of java.
// One line comment

/*
Multi-line comment
*/

8 Variables and types


8.1 Declarations
There are three kinds of declarations in JavaScript.
var : Declares a variable, optionally initializing it to a value.
let : Declares a block scope local variable, optionally initializing it to a value.
const : Declares a read-only named constant.

8.2 Declaring Variables


Variables in javascript are used for storing data.
Variables can be declared in two ways.
Using keyword var. For example, var x = 3. Both local and global variables can be
declared using this syntax.
Using keyword let. For example, let y = 5. Declares a block scope variable.

8.3 Variable Scope


A variable declared outside any function is a Global variable. This variable can be
accessed by any other code in the current document.
A variable declared within a function is a Local variable. This variable is only available to
the codes within the function.
A variable declared with the keyword let is available only inside the block in which it is
declared. The block can be anything, an if condition block, a for loop block, etc.

if (true) {
var x = 5;
}
alert('x= ' + x);

if (true) {
let y = 5;
}
alert('y= ' + y);

8.4 Variable Hoisting


In javascript, you refer to a variable declared later, without getting an exception.
The variables are hoisted to the top of the function or statements.
But the values of variables are not hoisted, i.e. their values become undefined.
Variables declared with keyword let are not hoisted.
alert('myvar= ' + myvar);
var myvar = 3;

alert('myvar1= ' + myvar1);


let myvar1 = 3;

8.5 Constants
These are read only variables.
Value of a constant cannot be changed using assignment. It cannot be re-declared.
It has to be initialized to a value
Constant with the same name of a function or variable cannot be declared in the same
scope.
Syntax: const pi = 3.14;

8.6 Data types.


There are six primitive data types in javascript.
Boolean : true or false.
null : Denotes null value. null is case sensitive so dont use Null or NULL.
undefined : Value is undefined.
Number : integer or float. Eg. 3, 1.5
String : Hey There!.
Object.

8.7 Data type conversion


JavaScript is a dynamically typed language. That means you don't have to specify the data type
of a variable when you declare it, and data types are converted automatically as needed during
script execution.

For converting strings to numbers, the following methods can be used.


parseInt()
parseFloat()

9 Strings
A string is zero or more characters enclosed in double (") or single (') quotation marks.
var firstname = "Vijay";
var middlename = "Dinanath";
var lastname = "Chauhan";

Special characters:
\n

New line

\t

Tab

\b

Backspace

Single quote

Double quote

\\

Backslash

9.1 String methods


9.1.1 The String length method:
The length property returns the length of a string.
var hello = "Hey there! How are you?";
var x = hello.length;
alert(x);

9.1.2 The indexOf() method:


This method returns the position of the first occurrence of the specified text.

9.1.3 The lastIndexOf() method:


This method returns the position of the last occurrence of the specified text.
var hello = "Hey there! Are you there?";
var x = hello.indexOf("there");
var y = hello.lastIndexOf("there");
alert("x= " + x + "\n" + "y= " + y);

9.1.4 The search method:


This method searches for the specified string and returns its position.
var hello = "Hey there! Are you there?";
var x = hello.search("there");
alert("x= " + x);

9.1.5 The replace method:


The replace() method replaces a specified value with another value in a string.
var hello = "Hey there! How are you
guys?";
var x = hello.replace("guys", "girls");
alert(x);

9.1.6 The toUpperCase() method and toLowerCase() method:


toUpperCase() method converts string to upper case and toLowerCase method converts string
to lower case.
var hello = "Hey There! How Are You?";
var upper = hello.toUpperCase();
var lower = hello.toLowerCase();
alert("upper= " + upper + "\n" + "lower=
" + lower);

9.1.7 The concat() method:


The concat() method joins two or more strings.
var hello1 = "Hey There!";
var hello2 = "How Are You?";
var hello3 = hello1.concat(" ", hello2);
alert(hello3);

10 Array
An array is a list of zero or more expressions, each of which represents an array element,
enclosed in square brackets [].
var chocolates = ["Toffee", "Candy", "Lollipop"];

This array has three elements, chocolate[0] is Toffee, chocolate[1] is Candy and
chocolate[2] is Lollipop.

10.1 Creating an array


There are two ways for creating array.
var chocolates = ["Toffee", "Candy", "Lollipop"];
var chocolates = new Array("Toffee", "Candy", "Lollipop");

10.2 Displaying array


var chocolates = new Array("Toffee",
"Candy", "Lollipop");
var x = chocolates[1];
alert(x);

10.3 Array Methods


10.3.1 The concat() method:
This method joins two arrays and returns a new array.
var fruit = new Array("Apple", "Mango");
var fruit_vege = fruit.concat("Potato",
"Onion");
alert(fruit_vege);

10.3.2 The join() method:


This method joins all elements of an array into a string.
var fruit = new Array("Apple", "Mango",
"Orange");
var list = fruit.join(" - ");
alert(list);

10.3.3 The push() method:


This method adds one or more elements to the end of an array and returns the resulting length
of the array.
var fruit = new Array("Apple", "Mango",
"Orange");
fruit.push("Grapes");
alert(fruit);

10.3.4 The pop() method:


This method removes the last element from an array and returns that element.
var fruit = new Array("Apple", "Mango",
"Orange");
var out = fruit.pop();
alert(fruit);

10.3.5 The shift() method:


This method removes the first element from an array and returns that element.
var fruit = new Array("Apple", "Mango",
"Orange");
var out = fruit.shift();
alert("out= "+ out + "\n fruit= " + fruit);

10.3.6 The unshift() method:


This method adds one or more elements to the front of an array and returns the new length of
the array.
var fruit = new Array("Apple", "Mango",
"Orange");
fruit.unshift("Grape", "Pineapple");
alert(fruit);

10.3.7 The reverse() method:


This method reverses the elements of an array. The first array element becomes the last and
the last becomes the first.
var fruit = new Array("Apple", "Mango",
"Orange");
fruit.reverse();
alert(fruit);

10.3.8 The sort() method:


This method sorts the elements of an array.
var fruit = new Array("Grapes", "Mango",
"Apple", "Orange");
fruit.sort();
alert(fruit);

10.3.9 The slice() method:


This method extracts a section of an array and returns a new array.
var fruit = new Array("Grapes", "Mango",
"Apple", "Orange", "Pineapple");
fruit = fruit.slice(2,4);
alert(fruit);

11 Object
An object is a list of zero or more pairs of property names and associated values of an object,
enclosed in curly braces {}.
A mobile is an object with properties such as name, model, color. This example given below
shows one such object with these properties.
The properties can also contain functions. These are called object methods.

Here the name property has value google, model property has value nexus-5x, color
property has value white and getinfo property contains the function which gives an alert
when it is called.
var mobile = { name: "google ",
model: "nexus-5x ",
color: "white ",
getinfo: function() {
alert(mobile.name + mobile.model +
mobile.color)}
};

mobile.getinfo();

12 Control flow statements


JavaScript supports a compact set of statements, specifically control flow statements, that you
can use to incorporate a great deal of interactivity in your application.

12.1 Block Statements


The most basic statement is a block statement that is used to group statements.
{
statement 1;
statement 2;
.
.
statement n;
}

Block statements are commonly used with control statements.

while (i < 5) {
i++;
}

Here { i++; } is a block statement.

12.2 Conditional statements


A conditional statement is a set of block statements that executes if a specified condition is
true. JavaScript supports two conditional statements: if...else and switch.

12.2.1 If..else statement :


If statement is used to execute a statement if a logical condition is true.
The else clause is used to execute a statement if the condition is false. The else clause is
optional.
if ( condition ) {
statement_1;
} else {
statement_2;
}

You can also add multiple conditions using else if clause.


if ( condition_1 ) {
statement_1;
} else if ( condition_2 ) {
statement_2;
} else if ( condition_3 ) {
statement_3;
} else if ( condition_n ) {
statement_n;
} else {
statement_else;
}

Example:
var result;
var marks = 80;
if ( marks > 90 ) {
result = "Excellent";
} else if ( marks > 70 ) {
result = "Very Good";
} else if ( marks > 50 ) {
result = "Good";
} else {
result = "Need practice";
}
alert("Result= " + result);

12.2.2 switch Statement :


A switch statement allows a program to evaluate an expression and attempt to match
the expression's value to a case label.
If a matching label is found, the program executes the associated statement.
If no matching label is found, the program looks for the optional default clause, and if it
is found, executes the associated statements.
If no default clause is found, the program continues execution at the statement
following the end of switch.
switch ( expression ) {
case label_1 : statements_1
break;
case label_2 : statements_2
break;
.
.
default :

statements_def
break;

The optional break statement associated with each case clause ensures that the
program breaks out of switch once the matched statement is executed and continues
execution of the statements following the switch.
If the break statement is omitted, the program continues to execute all the statements
in the case clause following the matching case clause.
Example
var fruit = "Bananas";
switch (fruit) {
case "Oranges":
alert("Oranges are Orange.");
break;
case "Apples":
alert("Apples are Red.");
break;
case "Bananas":
alert("Bananas are Yellow.");
break;
case "Guavas":
alert("Guavas are Green.");
break;
case "Blueberries":
alert("Blueberries are Blue.");
break;
default:
alert("Sorry, "+fruit+" was new for us!");
}

12.3 Exception handling statements


You can handle exceptions using try...catch statements.

try...catch statements
The try...catch statement groups a block of statements to try, and specifies one or more
responses exception that may get thrown.
If an exception is thrown, the try...catch statement catches it.
You will understand exception handling more properly from the following example.
var subjects = ["Physics", "Chemistry",
"Maths"];
var x = 0;
if ( subjects[x] ) {
alert("Subject "+x+" is
"+subject[x]);
}
var subjects = ["Physics", "Chemistry",
"Maths"];
var x = 0;
try{
if ( subjects[x] ) {
alert("Subject "+x+" is
"+subject[x]);
}
}
catch(e) {
alert("Subject code was incorrect.");
}

13 Loops and iteration


Loops are used to execute a set of statements particular number of times
JavaScript supports the following looping statements:
for statement
while statement
do...while statement
break statement
continue statement
for...in statement

13.1 for statement


A for loop repeats until a specified condition evaluates to false.
for ( initialization ; condition ; increment ) {
statements;
}

The flow of for loop is as follows


Initialization : This part is executed first. Here one or more loop counter variables are
initialized.
Condition : After initialization, condition expression is executed. If the value of condition
is true, the loop statements are executed. If the value of condition is false, the loop
terminates. If condition part is left blank, the condition is assumed to be true.
Statements: If the value of condition is true, the statements specified here are executed.
Multiple statements can be executed using block statement{...}.
Increment : After executing the statements, increment expression is executed to
increment the counter variables. After completing its execution the control returns to
step 2(condition) and the loop continues till condition becomes false.

Example
var i;
var x = 0;
for (i = 0; i < 5; i++) {
x = x + 5;
}
alert(x);

13.2 while statement


A while statement executes its statements as long as a specified condition evaluates to true.
If the condition becomes false, the loop terminates and control passes to the statement
following the loop.
while ( condition ) {
statements;
}

Example
var i = 0;
var hi = "Hi";
var ok = "Ok";
while(i<5) {
ok = ok.concat(" ", hi);
i++;
}
alert(ok);

13.3 do...while statement


A do...while loop repeats until a specified condition evaluates to false.
In do...while statement, the statements are executed once before the condition is checked.
do {
statements;
} while ( condition );

Example
var i = 0;
var hi = "Hi";
var ok = "Ok";
do {
ok = ok.concat(" ", hi);
i++;
} while(i<5);
alert(ok);

13.4 break statement


Use the break statement to terminate a loop or switch.
var i;
var cc = 2
var x = 0;
for (i = 0; i < 5; i++) {
x = x + 5;
if(i == cc) {
break;
}
}
alert(x);

13.5 continue statement


The continue statement can be used to restart a while, do...while or for loop.
var i = 0;
var hi = "Hi";
var ok = "Ok";
while(i<5) {
i++;
if(i == 1 || i == 3) {
continue;
}
ok = ok.concat(" ", hi);
}
alert(ok);

13.6 for...in statement


The for...in statement iterates a specified variable over all the enumerable properties of
an object.
For each distinct property, JavaScript executes the specified statements.
for ( variable in object) {
statements;
}

Example

var mobile = { name: "google ",


model: "nexus-5x ",
color: "white " };
var x;
var details = "";
for (x in mobile) {
details += mobile[x] + " ";
}
alert(details);

14 Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a set of
statements that performs a task.

14.1 Function declaration


Function declaration includes
Name of the function.
List of arguments to the function. These are enclosed in parentheses and are separated
by commas.
Javascript statements that define the function. These are enclosed in curly brackets{ }.
function function_name( arguments ) {
statements;
}

14.2 Calling function


Defining a function does not execute it. It simply names the function and specifies what to do
when the function is called. Calling the function actually performs the specified actions with the
indicated parameters.

14.3 Function return


When control reaches to return statement, the execution of the function stops. The function
returns the value specified in the return statement.
Example
function square(x) {
return x * x;
}
var x = 6;
alert(square(x));

14.4 Function Scope


Variables defined inside a function cannot be accessed from anywhere outside the
function.
A function defined in the global scope can access all variables defined in the global
scope.
A function defined inside another function can access all variables defined in its parent
function and any other variable to which the parent function has access.

14.5 Nested functions


The inner function can be accessed only from statements in the outer function.
The inner function can use the arguments and variables of the outer function, while the
outer function cannot use the arguments and variables of the inner function.
function magnitude(a, b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
var mag = magnitude(4,5);
alert(mag);

15 Operators
JavaScript consist of the following operators
Assignment operators
Comparison operators
Arithmetic operators
Bitwise operators
Logical operators
String operators
Conditional operator
Unary operator
Relational operator

15.1 Assignment operators


Assignment operator is used to assign value. Value is assigned to the left operand based on the
value of the right operand.
The simple assignment operator is equal (=) which assigns the value of the right operand to the
left operand.
Compound assignment operators (shorthand) are given below
Name

Shorthand operator

Meaning

Assignment

x = y

x = y

Addition assignment

x += y

x = x + y

Subtraction assignment

x -= y

x = x - y

Multiplication assignment

x *= y

x = x * y

Division assignment

x /= y

x = x / y

Remainder assignment

x %= y

x = x % y

Bitwise AND assignment

x &= y

x = x & y

Bitwise OR assignment

x |= y

x = x | y

15.2 Comparison operators


Comparison operator is used to compare operands.
It returns a logical value, i.e. true or false.
Operands can be numbers, strings, logical or object values.
If two operands are not of the same type, javascript attempts to convert them into an
appropriate type for the conversion. To avoid this and compare two operands with also

considering their type, the === and !== operators are used. These operators do not
attempt to convert the operands into compatible types before comparing.
Comparison operands are given below
Operator

Description

==

Equal value

!=

Not equal value

===

Equal value and equal type

!==

Not equal value or not equal type

>

Greater than

>=

Greater than or equal

<

Less than

<=

Less than or equal

15.3 Arithmetic operators


Arithmetic operators perform arithmetic operations on numerical values.
The arithmetic operators supported in javascript are listed below
Operator

Description

Addition

Subtraction

Multiplication

Division

Modulus (Remainder)

++

Increment

--

Decrement

15.4 Bitwise operators


Bitwise operators consider the operands as 32 bit number and not decimal, octal or
hexadecimal numbers. They perform bitwise operations on the operands.
Bitwise operators in javascript are listed below
Operator

Description

Example

Evaluation

&

AND

3 & 5

0011 & 0101 = 0001 (1)

OR

3 | 5

0011 | 0101 = 0111 (7)

XOR

3 ^ 5

0011 ^ 0101 = 0110 (6)

NOR

~3

~0011

= 1100 (12)

15.5 Logical operators


Logical operators are generally used with boolean values, hence in those cases they return
boolean values.
But the && and || operators return value of one of the specified operands so they may return
non-boolean value if they are used with non-boolean values.

Logical operators are listed below


Operator

Description

Example

&&

Logical AND

a == 5 && b == 7

||

Logical OR

a == 5 || b == 7

Logical NOT

!( a == 5 )

15.6 String operators


The concatenation (+) operator concatenates two strings together.
We can also use the shorthand assignment operator += for concatenation.
var x = "Hi " + "guys!";
alert(x);
var x = "Hi ";
x += "guys!";
alert(x);

15.7 Conditional operator


The conditional operator is the only ternary operator in javascript, i.e. it takes three operands.
condition ? value1 : value2;

If the condition is true the first value is assigned and if the condition is false the second value is
assigned.
Example
var class = ( age >= 18 ) ? "You can drive" : "No driving license!" ;

15.8 Unary operator


The typeof operator is a unary operator used to find the type of a particular operand.
typeof operand;

This returns the type of the operand in string type.


var x = 5;

Returns "number"

typeof x;
var y = "Hello";

Returns "string"

typeof y;

15.9 Relational operator


The instanceof operator is a relational operator which returns true if an object is an instance of
an object type.
objectName instanceof objectType;

Example
var tdate = new Date(1995, 12, 17);

Returns true since tdate is an instance

if ( tdate instanceof Date ) {

of date object.

// statements to execute
}

16 Numbers
There is only one type for numbers in javascript. They can be written with or without decimal.

16.1 Number systems


16.1.1 Decimal numbers
var x = 3;
var y = 4.5;

Very large or small numbers can be written with exponential notation.


var x = 315e5;

Here x = 31500000

var x = 315e-5

Here x = 0.00315

16.1.2 Binary numbers


Binary number syntax uses a leading zero followed by a lowercase or uppercase B (0b or 0B).
var bin1 = 0b0011 ;

Here bin1 = 3

var bin2 = 0B010011 ;

Here bin2 = 19

16.1.3 Hexadecimal numbers


Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase X (0x or
0X).
var hex1 = 0xA ;

Here hex1 = 10

var hex2 = 0X3F ;

Here bin2 = 63

16.1.4 NaN
NaN stands for Not a Number.
NaN is a JavaScript reserved word indicating that a value is not a number.
Trying to do arithmetic with a non-numeric string will result in NaN.
However if the string contains numeric value, the result will be numeric.
var x = 5 / "Hi";

Here x = NaN

var x = 20 / "5";

Here x = 4

16.2 Number object


The built-in Number object can also be used for defining numbers.
var variable_name = new Number(value)

16.2.1 Properties of numbers


Property

Description

Number.MAX_VALUE

Assigns largest representable number

Number.MIN_VALUE

Assigns smallest representable number

Number.NaN

Assigns NaN(Not a Number) value

Number.NEGATIVE_INFINITY

Negative infinity value

Number.POSITIVE_INFINITY

Positive infinity value

Example
var x = Number.MAX_VALUE;
alert(x);

16.2.2 Methods of Numbers


Method

Description

Number.parseInt()

Parses a string and returns an var x = "6.5";


integer.
Same as parseInt() function.

Number.parseFloat()

x = Number.parseInt(x);
alert(x);
// 6

Parses a string and returns an var x = "6.5";


floating point number.
Same as parseFloat()

Number.isInteger()

Example

Checks whether passed value


is an integer.

x = Number.parseFloat(x);
alert(x);
// 6.5
var x = 6;
x = Number.isInteger(x);
alert(x);
// true

Number.isNaN()

Checks whether passed value


is NaN.

var x = parseInt("hi");
x = Number.isNaN(x);
alert(x);
// true

toString()

Returns the number as a


string.

var x = 6;
x = x.toString();
alert(x);
// 6

toExponential()

Returns string representing

var x = 6;
x = x.toExponential();

the number in exponential

// 6e+0

notation.
toFixed()

Returns string representing


the number in fixed point

var x = 6.555555;
x = x.toFixed(4);
alert(x);

notation.
toPrecision()

alert(x);

// 6.5556

Returns number as a string


upto a specified precision in
fixed point notation.

var x = 6.555555;
x = x.toPrecision(4);
alert(x);
// 6.556

16.3 Math object


The built-in Math object has properties and methods for mathematical constants and functions.
Math.method_name(x)

var x = Math.pow(5, 2);

16.3.1 Methods of Math object


Method

Description

abs(x)

Returns absolute value

sin(x), cos(x), tan(x)

Trigonometric functions, arguments in


radians.

asin(x), acos(x), atan(x)

Inverse trigonometric functions, returns value


in radians.

sinh(x), cosh(x), tanh(x)

Hyperbolic trigonometric functions,


arguments in radians.

asinh(x), acosh(x), atanh(x)

Inverse hyperbolic trigonometric functions,


returns value in radians.

floor(x)

Returns the largest integer less than or equal


to argument.

ceil(x)

Returns the smallest integer greater than or


equal to argument.

pow(x,y)

Returns value where x is base and y is index


or power.

log(x), log10(x)

Logarithmic functions.

min(a,b,.,n), max(a,b,.,n)

Returns minimum/maximum value from


among the list of number arguments.

round(x)

Rounds to nearest integer.

sqrt(x)

Square root function.

random()

Returns a random value between 0 and 1.

17 Dates
There is no date data type in JavaScript but it consist of date object. You can use date object
and its methods to work with dates.

17.1 Date object


Date objects are created using the new Date() constructor.
var date_Object_Name = new Date(parameters);

Parameters can be as follows


Nothing: creates todays date and time.
A string representing date: the format is month day, year hours:minutes:seconds.
A set of integer values for year, month and day: new Date(1996, 10, 22). Here the
month will be November since the integer value for month argument is considered from
0, i.e, 0 as january, 1 as february and so on upto 11 as december.
A set of integer values for year, month, day, hour, minute and seconds: new Date(1996,
10, 22, 5, 30, 20). Even here 10 is considered as november.

17.2 Date object methods


17.2.1 Set methods
Method

Description

setDate()

Set the date as a number (1 to 31).

setFullYear()

Set the year

setMonth()

Set the month (0 to 11).

setHours()

Set hours (0 to 23)

setMinutes(), setSeconds()

Set minutes/seconds (0 to 59)

setTime()

Set time.

17.2.2 Get methods


Method

Description

getDate()

Get the date as a number (1 to 31).

getFullYear()

Get the year

getMonth()

Get the month (0 to 11).

getHours()

Get hours (0 to 23)

getMinutes(), setSeconds()

Get minutes/seconds (0 to 59)

getTime()

Get time.

Examples
setDate()

var tdy = new Date();

getDate()

tdy.setDate(15);
alert(tdy.getDate());

setFullYear()

var tdy = new Date();

getFullYear()

tdy.setFullYear(1992);
alert(tdy.getFullYear());

setHours()

var tdy = new Date();

getHours()

tdy.setHours(13);
alert(tdy.getHours());

17.2.3 Parsing method


A valid date string can be converted into date object using Date.parse() method.
Date.parse() method converts the string into milliseconds.
Then the number of milliseconds can be converted into date object.
var nx = Date.parse("April 11,
2014");
var tdy = new Date(nx);
alert(tdy);

18 Regular expressions
A regular expression is a sequence of characters that forms a pattern.
These patterns are used with methods of RegExp and String.
There are two ways of creating regular expression.
var re = /ax+by/;
var re = new RegExp("ax+by");

While searching, to make the search case-insensitive, the i modifier is used.


var x = /javascript/i;

18.1 RegExp with String methods


search() and replace() string methods are used with regular expressions.
The search() method searches for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
var hello = "Hey THERE! Are you there?";
var x = hello.search(/there/i);
alert("x= " + x);

var hello = "How are you GUYS ?";


var x = hello.replace(/guys/i, "Girls");
alert("x= " + x);

Regular expressions make search much more powerful. There are some more modifiers which
can be used.

18.2 Modifiers
Modifier

Description

Used for case-insensitive search.

Global match. Keeps on searching for more


matches after first match rather than
stopping.

Used for multiline match

18.3 Patterns
18.3.1 Brackets
Finds a range of characters
Expression

Description

[mno]

Matches any one of the characters in the


brackets.

[a-e]

Performs match as [abcde]

(1|3)

Finds any of the alternative separated by |

18.3.2 Quantifiers
Quantifiers

Description

a+

Matches any string containing at least one a

a*

Matches any string that contains zero or


more than zero times a

a?

Matches any string that contains zero or one


occurrence of a

18.3.3 Metacharacters
Metacharacter

Description

\d

Used to find digit.

\s

Matches a whitespace character

\b

Used to find a match at the beginning or at


the end of a word

18.4 RegExp Object


The RegExp object is the regular expression object.

18.4.1 test() method:


The test() method searches for a specified pattern. It returns true or false depending on the
result of the search.
var hello = "How are you guys?";
var re = new RegExp(/a/i);
var x = re.test(hello);
alert("x= " + x);

18.4.2 exec() method:


The exec() method searches for a specified pattern. However unlike test() method, it returns
the found text.
var hello = "How are you guys?";
var re = new RegExp(/a/i);
var x = re.exec(hello);
alert("x= " + x);

Thats it guys. If you have understood this module, you can easily code in JavaScript. Ill keep
updating the document to make it more better and easy to understand.

You might also like