Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

3 - Javascript Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 174

JAVASCRIPT NOTES

JavaScript is the most popular and widely used client-side scripting language. Client-side
scripting refers to scripts that run within your web browser. JavaScript is designed to add
interactivity and dynamic effects to the web pages by manipulating the content returned from
a web server. JavaScript was originally developed as LiveScript by Netscape in the mid 1990s.
It was later renamed to JavaScript in 1995, and became an ECMA standard in 1997. Now
JavaScript is the standard client-side scripting language for web-based applications, and it is
supported by virtually all web browsers available today, such as Google Chrome, Mozilla
Firefox, Apple Safari, etc. JavaScript is an object-oriented language, and it also has some
similarities in syntax to Java programming language. But, JavaScript is not related to Java in
any way. JavaScript is officially maintained by ECMA (European Computer Manufacturers
Association) as ECMAScript. ECMAScript 6 (or ES6) is the latest major version of the
ECMAScript standard.

What You Can Do with JavaScript


There are lot more things you can do with JavaScript.

 You can modify the content of a web page by adding or removing elements.
 You can change the style and position of the elements on a web page.
 You can monitor events like mouse click, hover, etc. and react to it.
 You can perform and control transitions and animations.
 You can create alert pop-ups to display info or warning messages to the user.
 You can perform operations based on user inputs and display the results.
 You can validate user inputs before submitting it to the server.

The list does not end here, there are many other interesting things that you can do with
JavaScript. You will learn about all of them in detail in upcoming chapters.

What This Tutorial Covers


This JavaScript tutorial series covers all the fundamental programming concepts, including
data types, operators, creating and using variables, generating outputs, structuring your code
to make decisions in your programs or to loop over the same block of code multiple times,
creating and manipulating strings and arrays, defining and calling functions, and so on.

Once you're comfortable with the basics, you'll move on to next level that explains the idea of
objects, the Document Object Model (DOM) and Browser Object Model (BOM), as well as how
to make use of the native JavaScript objects like Date, Math, etc., and perform type
conversions. Finally, you'll explore some advanced concepts like event listeners, event
propagation, borrowing methods from other objects, hoisting behavior of JavaScript,
encoding and decoding JSON data, as well as detailed overview of new features introduced in
ECMAScript 6 (or ES6).

JavaScript Getting Started


Getting Started with JavaScript
Here, you will learn how easy it is to add interactivity to a web page using JavaScript. But,
before we begin, make sure that you have some working knowledge of HTML and CSS.

If you're just starting out in the world of web development, start learning from here »

Well, let's get started with the most popular client-side scripting language.

Adding JavaScript to Your Web Pages


There are typically three ways to add JavaScript to a web page:

 Embedding the JavaScript code between a pair of <script> and </script> tag.
 Creating an external JavaScript file with the .js extension and then load it within the
page through the src attribute of the <script> tag.
 Placing the JavaScript code directly inside an HTML tag using the special tag attributes
such as onclick, onmouseover, onkeypress, onload, etc.

The following sections will describe each of these procedures in detail:

Embedding the JavaScript Code


You can embed the JavaScript code directly within your web pages by placing it between
the <script> and </script> tags. The <script> tag indicates the browser that the contained
statements are to be interpreted as executable script and not HTML. Here's an example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Embedding JavaScript</title>
</head>
<body>
<script>
var greet = "Hello World!";
document.write(greet); // Prints: Hello World!
</script>
</body>
</html>
The JavaScript code in the above example will simply prints a text message on the web page.
You will learn what each of these JavaScript statements means in upcoming chapters.

Note: The type attribute for <script> tag (i.e. <script type="text/javascript">) is no
longer required since HTML5. JavaScript is the default scripting language for HTML5.

Calling an External JavaScript File


You can also place your JavaScript code into a separate file with a .js extension, and then call
that file in your document through the src attribute of the <script> tag, like this:
<script src="js/hello.js"></script>

This is useful if you want the same scripts available to multiple documents. It saves you from
repeating the same task over and over again, and makes your website much easier to
maintain.

Well, let's create a JavaScript file named "hello.js" and place the following code in it:

Example
Try this code »
// A function to display a message
function sayHello() {
alert("Hello World!");
}

// Call function on click of the button


document.getElementById("myBtn").onclick = sayHello;
Now, you can call this external JavaScript file within a web page using the <script> tag, like
this:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Including External JavaScript File</title>
</head>
<body>
<button type="button" id="myBtn">Click Me</button>
<script src="js/hello.js"></script>
</body>
</html>
Note: Usually when an external JavaScript file is downloaded for first time, it is stored in the
browser's cache (just like images and style sheets), so it won't need to be downloaded
multiple times from the web server that makes the web pages load more quickly.

Placing the JavaScript Code Inline


You can also place JavaScript code inline by inserting it directly inside the HTML tag using the
special tag attributes such as onclick, onmouseover, onkeypress, onload, etc. However, you
should avoid placing large amount of JavaScript code inline as it clutters up your HTML with
JavaScript and makes your JavaScript code difficult to maintain. Here's an example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inlining JavaScript</title>
</head>
<body>
<button onclick="alert('Hello World!')">Click Me</button>
</body>
</html>
The above example will show you an alert message on click of the button element.

Tip: You should always keep the content and structure of your web page (i.e. HTML) separate
out from presentation (CSS), and behavior (JavaScript).

Positioning of Script inside HTML Document


The <script> element can be placed in the <head>, or <body> section of an HTML document.
But ideally, scripts should be placed at the end of the body section, just before the
closing </body> tag, it will make your web pages load faster, since it prevents obstruction of
initial page rendering.

Each <script> tag blocks the page rendering process until it has fully downloaded and
executed the JavaScript code, so placing them in the head section (i.e. <head> element) of the
document without any valid reason will significantly impact your website performance.
Tip: You can place any number of <script> element in a single document. However, they are
processed in the order in which they appear in the document, from top to bottom.

Difference Between Client-side and Server-side


Scripting
Client-side scripting languages such as JavaScript, VBScript, etc. are interpreted and executed
by the web browser, while server-side scripting languages such as PHP, ASP, Java, Python,
Ruby, etc. runs on the web server and the output sent back to the web browser in HTML
format. Client-side scripting has many advantages over traditional server-side scripting
approach. For example, you can use JavaScript to check if the user has entered invalid data in
form fields and show notifications for input errors accordingly in real-time before submitting
the form to the web-server for final data validation and further processing in order to prevent
unnecessary network bandwidth usages and the exploitation of server system resources. Also,
response from a server-side script is slower as compared to a client-side script, because
server-side scripts are processed on the remote computer not on the user's local computer.

JavaScript Syntax
Understanding the JavaScript Syntax
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript
program.

A JavaScript consists of JavaScript statements that are placed within


the <script></script> HTML tags in a web page, or within the external JavaScript file
having .js extension.

The following example shows how JavaScript statements look like:

Example
Try this code »
var x = 5;
var y = 10;
var sum = x + y;
document.write(sum); // Prints variable value
You will learn what each of these statements means in upcoming chapters.
Case Sensitivity in JavaScript
JavaScript is case-sensitive. This means that variables, language keywords, function names,
and other identifiers must always be typed with a consistent capitalization of letters.

For example, the variable myVar must be typed myVar not MyVar or myvar. Similarly, the method
name getElementById() must be typed with the exact case not as getElementByID().

Example
Try this code »
var myVar = "Hello World!";
console.log(myVar);
console.log(MyVar);
console.log(myvar);
If you checkout the browser console by pressing the f12 key on the keyboard, you'll see a line
something like this: "Uncaught ReferenceError: MyVar is not defined".

JavaScript Comments
A comment is simply a line of text that is completely ignored by the JavaScript interpreter.
Comments are usually added with the purpose of providing extra information pertaining to
source code. It will not only help you understand your code when you look after a period of
time but also others who are working with you on the same project.

JavaScript support single-line as well as multi-line comments. Single-line comments begin


with a double forward slash (//), followed by the comment text. Here's an example:

Example
Try this code »
// This is my first JavaScript program
document.write("Hello World!");
Whereas, a multi-line comment begins with a slash and an asterisk (/*) and ends with an
asterisk and slash (*/). Here's an example of a multi-line comment.

Example
Try this code »
/* This is my first program
in JavaScript */
document.write("Hello World!");
Understanding the JavaScript Syntax
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript
program.

A JavaScript consists of JavaScript statements that are placed within


the <script></script> HTML tags in a web page, or within the external JavaScript file
having .js extension.

The following example shows how JavaScript statements look like:

Example
Try this code »
var x = 5;
var y = 10;
var sum = x + y;
document.write(sum); // Prints variable value
You will learn what each of these statements means in upcoming chapters.

Case Sensitivity in JavaScript


JavaScript is case-sensitive. This means that variables, language keywords, function names,
and other identifiers must always be typed with a consistent capitalization of letters.

For example, the variable myVar must be typed myVar not MyVar or myvar. Similarly, the method
name getElementById() must be typed with the exact case not as getElementByID().

Example
Try this code »
var myVar = "Hello World!";
console.log(myVar);
console.log(MyVar);
console.log(myvar);
If you checkout the browser console by pressing the f12 key on the keyboard, you'll see a line
something like this: "Uncaught ReferenceError: MyVar is not defined".

JavaScript Comments
A comment is simply a line of text that is completely ignored by the JavaScript interpreter.
Comments are usually added with the purpose of providing extra information pertaining to
source code. It will not only help you understand your code when you look after a period of
time but also others who are working with you on the same project.
JavaScript support single-line as well as multi-line comments. Single-line comments begin
with a double forward slash (//), followed by the comment text. Here's an example:

Example
Try this code »
// This is my first JavaScript program
document.write("Hello World!");
Whereas, a multi-line comment begins with a slash and an asterisk (/*) and ends with an
asterisk and slash (*/). Here's an example of a multi-line comment.

Example
Try this code »
/* This is my first program
in JavaScript */
document.write("Hello World!");

JavaScript Variables. What is Variable?


Variables are fundamental to all programming languages. Variables are used to store data,
like string of text, numbers, etc. The data or value stored in the variables can be set, updated,
and retrieved whenever needed. In general, variables are symbolic names for values.

You can create a variable with the var keyword, whereas the assignment operator (=) is used to
assign value to a variable, like this: var varName = value;

Example
Try this code »
var name = "Peter Parker";
var age = 21;
var isMarried = false;
Tip: Always give meaningful names to your variables. Additionally, for naming the variables
that contain multiple words, camelCase is commonly used. In this convention all words after
the first should have uppercase first letters, e.g. myLongVariableName.

In the above example we have created three variables, first one has assigned with a string
value, the second one has assigned with a number, whereas the last one assigned with a
boolean value. Variables can hold different types of data, we'll learn about them in later
chapter.

In JavaScript, variables can also be declared without having any initial values assigned to
them. This is useful for variables which are supposed to hold values like user inputs.
Example
Try this code »
// Declaring Variable
var userName;

// Assigning value
userName = "Clark Kent";
Note: In JavaScript, if a variable has been declared, but has not been assigned a value
explicitly, is automatically assigned the value undefined.

Declaring Multiple Variables at Once


In addition, you can also declare multiple variables and set their initial values in a single
statement. Each variable are separated by commas, as demonstrated in the following example:

Example
Try this code »
// Declaring multiple Variables
var name = "Peter Parker", age = 21, isMarried = false;

/* Longer declarations can be written to span


multiple lines to improve the readability */
var name = "Peter Parker",
age = 21,
isMarried = false;

The let and const Keywords


ES6 introduces two new keywords let and const for declaring variables.

The const keyword works exactly the same as let, except that variables declared
using const keyword cannot be reassigned later in the code. Here's an example:

Example
Try this code »
// Declaring variables
let name = "Harry Potter";
let age = 11;
let isStudent = true;

// Declaring constant
const PI = 3.14;
console.log(PI); // 3.14
// Trying to reassign
PI = 10; // error
Unlike var, which declare function-scoped variables, both let and const keywords declare
variables, scoped at block-level ({}). Block scoping means that a new scope is created between
a pair of curly brackets {}. We'll discuss this in detail later, in JavaScript ES6 features chapter.

Naming Conventions for JavaScript Variables


These are the following rules for naming a JavaScript variable:

 A variable name must start with a letter, underscore (_), or dollar sign ($).
 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters (A-z, 0-9) and underscores.
 A variable name cannot contain spaces.
 A variable name cannot be a JavaScript keyword or a JavaScript reserved word.

Note: Variable names in JavaScript are case sensitive, it means $myvar and $myVar are two
different variables. So be careful while defining variable names.

JavaScript Generating Output


Generating Output in JavaScript
There are certain situations in which you may need to generate output from your JavaScript
code. For example, you might want to see the value of variable, or write a message to browser
console to help you debug an issue in your running JavaScript code, and so on.

In JavaScript there are several different ways of generating output including writing output to
the browser window or browser console, displaying output in dialog boxes, writing output
into an HTML element, etc. We'll take a closer look at each of these in the following sections.

Writing Output to Browser Console


You can easily outputs a message or writes data to the browser console using
the console.log() method. This is a simple, but very powerful method for generating detailed
output. Here's an example:

Example
Try this code »
// Printing a simple text message
console.log("Hello World!"); // Prints: Hello World!
// Printing a variable value
var x = 10;
var y = 20;
var sum = x + y;
console.log(sum); // Prints: 30
Tip: To access your web browser's console, first press F12 key on the keyboard to open
the developer tools then click on the console tab. It looks something like the screenshot here.

Displaying Output in Alert Dialog Boxes


You can also use alert dialog boxes to display the message or output data to the user. An alert
dialog box is created using the alert() method. Here's is an example:

Example
Try this code »
// Displaying a simple text message
alert("Hello World!"); // Outputs: Hello World!

// Displaying a variable value


var x = 10;
var y = 20;
var sum = x + y;
alert(sum); // Outputs: 30

Writing Output to the Browser Window


You can use the document.write() method to write the content to the current document only
while that document is being parsed. Here's an example:

Example
Try this code »
// Printing a simple text message
document.write("Hello World!"); // Prints: Hello World!

// Printing a variable value


var x = 10;
var y = 20;
var sum = x + y;
document.write(sum); // Prints: 30
If you use the document.write() method method after the page has been loaded, it will
overwrite all the existing content in that document. Check out the following example:

Example
Try this code »
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>

<button type="button" onclick="document.write('Hello World!')">Click


Me</button>

Inserting Output Inside an HTML Element


You can also write or insert output inside an HTML element using the
element's innerHTML property. However, before writing the output first we need to select the
element using a method such as getElementById(), as demonstrated in the following example:

Example
Try this code »
<p id="greet"></p>
<p id="result"></p>

<script>
// Writing text string inside an element
document.getElementById("greet").innerHTML = "Hello World!";

// Writing a variable value inside an element


var x = 10;
var y = 20;
var sum = x + y;
document.getElementById("result").innerHTML = sum;
</script>

JavaScript Data Types. Data Types in JavaScript


Data types basically specify what kind of data can be stored and manipulated within a
program. There are six basic data types in JavaScript which can be divided into three main
categories: primitive (or primary), composite (or reference), and special data types. String,
Number, and Boolean are primitive data types. Object, Array, and Function (which are all types
of objects) are composite data types. Whereas Undefined and Null are special data types.

Primitive data types can hold only one value at a time, whereas composite data types can hold
collections of values and more complex entities. Let's discuss each one of them in detail.

The String Data Type


The string data type is used to represent textual data (i.e. sequences of characters). Strings are
created using single or double quotes surrounding one or more characters, as shown below:
Example
Try this code »
var a = 'Hi there!'; // using single quotes
var b = "Hi there!"; // using double quotes
You can include quotes inside the string as long as they don't match the enclosing quotes.

Example
Try this code »
var a = "Let's have a cup of coffee."; // single quote inside double
quotes
var b = 'He said "Hello" and left.'; // double quotes inside single
quotes
var c = 'We\'ll never give up.'; // escaping single quote with
backslash
You will learn more about the strings in JavaScript strings chapter.

The Number Data Type


The number data type is used to represent positive or negative numbers with or without
decimal place, or numbers written using exponential notation e.g. 1.5e-4 (equivalent to
1.5x10-4).

Example
Try this code »
var a = 25; // integer
var b = 80.5; // floating-point number
var c = 4.25e+6; // exponential notation, same as 4.25e6 or 4250000
var d = 4.25e-6; // exponential notation, same as 0.00000425
The Number data type also includes some special values which are: Infinity, -Infinity and NaN.
Infinity represents the mathematical Infinity ∞, which is greater than any number. Infinity is the
result of dividing a nonzero number by 0, as demonstrated below:

Example
Try this code »
alert(16 / 0); // Output: Infinity
alert(-16 / 0); // Output: -Infinity
alert(16 / -0); // Output: -Infinity
While NaN represents a special Not-a-Number value. It is a result of an invalid or an undefined
mathematical operation, like taking the square root of -1 or dividing 0 by 0, etc.
Example
Try this code »
alert("Some text" / 2); // Output: NaN
alert("Some text" / 2 + 10); // Output: NaN
alert(Math.sqrt(-1)); // Output: NaN
You will learn more about the numbers in JavaScript numbers chapter.

The Boolean Data Type


The Boolean data type can hold only two values: true or false. It is typically used to store
values like yes (true) or no (false), on (true) or off (false), etc. as demonstrated below:

Example
Try this code »
var isReading = true; // yes, I'm reading
var isSleeping = false; // no, I'm not sleeping
Boolean values also come as a result of comparisons in a program. The following example
compares two variables and shows the result in an alert dialog box:

Example
Try this code »
var a = 2, b = 5, c = 10;

alert(b > a) // Output: true


alert(b > c) // Output: false
You will learn more about the comparisons in JavaScript if/else chapter.

The Undefined Data Type


The undefined data type can only have one value-the special value undefined. If a variable has
been declared, but has not been assigned a value, has the value undefined.

Example
Try this code »
var a;
var b = "Hello World!"

alert(a) // Output: undefined


alert(b) // Output: Hello World!
The Null Data Type
This is another special data type that can have only one value-the null value. A null value
means that there is no value. It is not equivalent to an empty string ( "") or 0, it is simply
nothing.

A variable can be explicitly emptied of its current contents by assigning it the null value.

Example
Try this code »
var a = null;
alert(a); // Output: null

var b = "Hello World!"


alert(b); // Output: Hello World!

b = null;
alert(b) // Output: null

The Object Data Type


The object is a complex data type that allows you to store collections of data. An object
contains properties, defined as a key-value pair. A property key (name) is always a string, but
the value can be any data type, like strings, numbers, booleans, or complex data types like
arrays, function and other objects. You'll learn more about objects in upcoming chapters.

The following example will show you the simplest way to create an object in JavaScript.

Example
Try this code »
var emptyObject = {};
var person = {"name": "Clark", "surname": "Kent", "age": "36"};

// For better reading


var car = {
"modal": "BMW X3",
"color": "white",
"doors": 5
}
You can omit the quotes around property name if the name is a valid JavaScript name. That
means quotes are required around "first-name" but are optional around firstname. So the car
object in the above example can also be written as:
Example
Try this code »
var car = {
modal: "BMW X3",
color: "white",
doors: 5
}

The Array Data Type


An array is a type of object used for storing multiple values in single variable. Each value (also
called an element) in an array has a numeric position, known as its index, and it may contain
data of any data type-numbers, strings, booleans, functions, objects, and even other arrays.
The array index starts from 0, so that the first array element is arr[0] not arr[1].

The simplest way to create an array is by specifying the array elements as a comma-separated
list enclosed by square brackets, as shown in the example below:

Example
Try this code »
var colors = ["Red", "Yellow", "Green", "Orange"];
var cities = ["London", "Paris", "New York"];

alert(colors[0]); // Output: Red


alert(cities[2]); // Output: New York
You will learn more about the arrays in JavaScript arrays chapter.

The Function Data Type


The function is callable object that executes a block of code. Since functions are objects, so it
is possible to assign them to variables, as shown in the example below:

Example
Try this code »
var greeting = function(){
return "Hello World!";
}

// Check the type of greeting variable


alert(typeof greeting) // Output: function
alert(greeting()); // Output: Hello World!
In fact, functions can be used at any place any other value can be used. Functions can be
stored in variables, objects, and arrays. Functions can be passed as arguments to other
functions, and functions can be returned from functions. Consider the following function:

Example
Try this code »
function createGreeting(name){
return "Hello, " + name;
}
function displayGreeting(greetingFunction, userName){
return greetingFunction(userName);
}

var result = displayGreeting(createGreeting, "Peter");


alert(result); // Output: Hello, Peter
You will learn more about the functions in JavaScript functions chapter.

The typeof Operator


The typeof operator can be used to find out what type of data a variable or operand contains.
It can be used with or without parentheses (typeof(x) or typeof x).

The typeof operator is particularly useful in the situations when you need to process the values
of different types differently, but you need to be very careful, because it may produce
unexpected result in some cases, as demonstrated in the following example:

Example
Try this code »
// Numbers
typeof 15; // Returns: "number"
typeof 42.7; // Returns: "number"
typeof 2.5e-4; // Returns: "number"
typeof Infinity; // Returns: "number"
typeof NaN; // Returns: "number". Despite being "Not-A-Number"

// Strings
typeof ''; // Returns: "string"
typeof 'hello'; // Returns: "string"
typeof '12'; // Returns: "string". Number within quotes is typeof string

// Booleans
typeof true; // Returns: "boolean"
typeof false; // Returns: "boolean"

// Undefined
typeof undefined; // Returns: "undefined"
typeof undeclaredVariable; // Returns: "undefined"
// Null
typeof Null; // Returns: "object"

// Objects
typeof {name: "John", age: 18}; // Returns: "object"

// Arrays
typeof [1, 2, 4]; // Returns: "object"

// Functions
typeof function(){}; // Returns: "function"
As you can clearly see in the above example when we test the null value using
the typeof operator (line no-22), it returned "object" instead of "null". This is a long-standing
bug in JavaScript, but since lots of codes on the web written around this behavior, and thus
fixing it would create a lot more problem, so idea of fixing this issue was rejected by the
committee that design and maintains JavaScript.

JavaScript Operators. What are Operators in


JavaScript
Operators are symbols or keywords that tell the JavaScript engine to perform some sort of
actions. For example, the addition (+) symbol is an operator that tells JavaScript engine to add
two variables or values, while the equal-to (==), greater-than (>) or less-than (<) symbols are
the operators that tells JavaScript engine to compare two variables or values, and so on.

The following sections describe the different operators used in JavaScript.

JavaScript Arithmetic Operators


The arithmetic operators are used to perform common arithmetical operations, such as
addition, subtraction, multiplication etc. Here's a complete list of JavaScript's arithmetic
operators:

Operator Description Example Result

+ Addition x + y Sum of x and y

- Subtraction x - y Difference of x and y.

* Multiplication x * y Product of x and y.

/ Division x / y Quotient of x and y


% Modulus x % y Remainder of x divided by y

The following example will show you these arithmetic operators in action:

Example
Try this code »
var x = 10;
var y = 4;
alert(x + y); // 0utputs: 14
alert(x - y); // 0utputs: 6
alert(x * y); // 0utputs: 40
alert(x / y); // 0utputs: 2.5
alert(x % y); // 0utputs: 2

JavaScript Assignment Operators


The assignment operators are used to assign values to variables.

Operator Description Example Is The Same As

= Assign x = y x = y

+= Add and assign x += y x = x + y

-= Subtract and assign x -= y x = x - y

*= Multiply and assign x *= y x = x * y

/= Divide and assign quotient x /= y x = x / y

%= Divide and assign modulus x %= y x = x % y

The following example will show you these assignment operators in action:

Example
Try this code »
var x; // Declaring Variable

x = 10;
alert(x); // Outputs: 10

x = 20;
x += 30;
alert(x); // Outputs: 50
x = 50;
x -= 20;
alert(x); // Outputs: 30

x = 5;
x *= 25;
alert(x); // Outputs: 125

x = 50;
x /= 10;
alert(x); // Outputs: 5

x = 100;
x %= 15;
alert(x); // Outputs: 10

JavaScript String Operators


There are two operators which can also used be for strings.

Operator Description Example Result

+ Concatenation str1 + str2 Concatenation of str1 and str2

+= Concatenation assignment str1 += str2 Appends the str2 to the str1

The following example will show you these string operators in action:

Example
Try this code »
var str1 = "Hello";
var str2 = " World!";

alert(str1 + str2); // Outputs: Hello World!

str1 += str2;
alert(str1); // Outputs: Hello World!

JavaScript Incrementing and Decrementing Operators


The increment/decrement operators are used to increment/decrement a variable's value.

Operator Name Effect

++x Pre-increment Increments x by one, then returns x


x++ Post-increment Returns x, then increments x by one

--x Pre-decrement Decrements x by one, then returns x

x-- Post-decrement Returns x, then decrements x by one

The following example will show you how increment and decrement operators actually work:

Example
Try this code »
var x; // Declaring Variable

x = 10;
alert(++x); // Outputs: 11
alert(x); // Outputs: 11

x = 10;
alert(x++); // Outputs: 10
alert(x); // Outputs: 11

x = 10;
alert(--x); // Outputs: 9
alert(x); // Outputs: 9

x = 10;
alert(x--); // Outputs: 10
alert(x); // Outputs: 9

JavaScript Logical Operators


The logical operators are typically used to combine conditional statements.

Operator Name Example Result

&& And x && y True if both x and y are true

|| Or x || y True if either x or y is true

! Not !x True if x is not true

The following example will show you how these logical operators actually work:

Example
Try this code »
var year = 2018;
// Leap years are divisible by 400 or by 4 but not 100
if((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))){
alert(year + " is a leap year.");
} else{
alert(year + " is not a leap year.");
}

JavaScript Comparison Operators


The comparison operators are used to compare two values in a Boolean fashion.

Operator Name Example Result

== Equal x == y True if x is equal to y

=== Identical x === y True if x is equal to y, and they are of the same type

!= Not equal x != y True if x is not equal to y

!== Not identical x !== y True if x is not equal to y, or they are not of the same type

< Less than x < y True if x is less than y

> Greater than x > y True if x is greater than y

>= Greater than or equal to x >= y True if x is greater than or equal to y

<= Less than or equal to x <= y True if x is less than or equal to y

The following example will show you these comparison operators in action:

Example
Try this code »
var x = 25;
var y = 35;
var z = "25";

alert(x == z); // Outputs: true


alert(x === z); // Outputs: false
alert(x != y); // Outputs: true
alert(x !== z); // Outputs: true
alert(x < y); // Outputs: true
alert(x > y); // Outputs: false
alert(x <= y); // Outputs: true
alert(x >= y); // Outputs: false
JavaScript Events
Understanding Events and Event Handlers
An event is something that happens when user interact with the web page, such as when he
clicked a link or button, entered text into an input box or textarea, made selection in a select
box, pressed key on the keyboard, moved the mouse pointer, submits a form, etc. In some
cases, the Browser itself can trigger the events, such as the page load and unload events.

When an event occur, you can use a JavaScript event handler (or an event listener) to detect
them and perform specific task or set of tasks. By convention, the names for event handlers
always begin with the word "on", so an event handler for the click event is called onclick,
similarly an event handler for the load event is called onload, event handler for the blur event is
called onblur, and so on.

There are several ways to assign an event handler. The simplest way is to add them directly to
the start tag of the HTML elements using the special event-handler attributes. For example, to
assign a click handler for a button element, we can use onclick attribute, like this:

Example
Try this code »
<button type="button" onclick="alert('Hello World!')">Click Me</button>
However, to keep the JavaScript seperate from HTML, you can set up the event handler in an
external JavaScript file or within the <script> and </script> tags, like this:

Example
Try this code »
<button type="button" id="myBtn">Click Me</button>
<script>
function sayHello() {
alert('Hello World!');
}
document.getElementById("myBtn").onclick = sayHello;
</script>
Note: Since HTML attributes are case-insensitive so onclick may also be written
as onClick, OnClick or ONCLICK. But its value is case-sensitive.

In general, the events can be categorized into four main groups — mouse events, keyboard
events, form events and document/window events. There are many other events, we will learn
about them in later chapters. The following section will give you a brief overview of the most
useful events one by one along with the real life practice examples.
Mouse Events
A mouse event is triggered when the user click some element, move the mouse pointer over
an element, etc. Here're some most important mouse events and their event handler.

The Click Event (onclick)


The click event occurs when a user clicks on an element on a web page. Often, these are form
elements and links. You can handle a click event with an onclick event handler.

The following example will show you an alert message when you click on the elements.

Example
Try this code »
<button type="button" onclick="alert('You have clicked a button!');">Click
Me</button>
<a href="#" onclick="alert('You have clicked a link!');">Click Me</a>

The Contextmenu Event (oncontextmenu)


The contextmenu event occurs when a user clicks the right mouse button on an element to
open a context menu. You can handle a contextmenu event with an oncontextmenu event
handler.

The following example will show an alert message when you right-click on the elements.

Example
Try this code »
<button type="button" oncontextmenu="alert('You have right-clicked a
button!');">Right Click on Me</button>
<a href="#" oncontextmenu="alert('You have right-clicked a link!');">Right
Click on Me</a>

The Mouseover Event (onmouseover)


The mouseover event occurs when a user moves the mouse pointer over an element.

You can handle the mouseover event with the onmouseover event handler. The following
example will show you an alert message when you place mouse over the elements.

Example
Try this code »
<button type="button" onmouseover="alert('You have placed mouse pointer
over a button!');">Place Mouse Over Me</button>
<a href="#" onmouseover="alert('You have placed mouse pointer over a
link!');">Place Mouse Over Me</a>

The Mouseout Event (onmouseout)


The mouseout event occurs when a user moves the mouse pointer outside of an element.

You can handle the mouseout event with the onmouseout event handler. The following example
will show you an alert message when the mouseout event occurs.

Example
Try this code »
<button type="button" onmouseout="alert('You have moved out of the
button!');">Place Mouse Inside Me and Move Out</button>
<a href="#" onmouseout="alert('You have moved out of the link!');">Place
Mouse Inside Me and Move Out</a>

Keyboard Events
A keyboard event is fired when the user press or release a key on the keyboard. Here're some
most important keyboard events and their event handler.

The Keydown Event (onkeydown)


The keydown event occurs when the user presses down a key on the keyboard.

You can handle the keydown event with the onkeydown event handler. The following example
will show you an alert message when the keydown event occurs.

Example
Try this code »
<input type="text" onkeydown="alert('You have pressed a key inside text
input!')">
<textarea onkeydown="alert('You have pressed a key inside
textarea!')"></textarea>

The Keyup Event (onkeyup)


The keyup event occurs when the user releases a key on the keyboard.

You can handle the keyup event with the onkeyup event handler. The following example will
show you an alert message when the keyup event occurs.
Example
Try this code »
<input type="text" onkeyup="alert('You have released a key inside text
input!')">
<textarea onkeyup="alert('You have released a key inside
textarea!')"></textarea>

The Keypress Event (onkeypress)


The keypress event occurs when a user presses down a key on the keyboard that has a
character value associated with it. For example, keys like Ctrl, Shift, Alt, Esc, Arrow keys, etc.
will not generate a keypress event, but will generate a keydown and keyup event.

You can handle the keypress event with the onkeypress event handler. The following example
will show you an alert message when the keypress event occurs.

Example
Try this code »
<input type="text" onkeypress="alert('You have pressed a key inside text
input!')">
<textarea onkeypress="alert('You have pressed a key inside
textarea!')"></textarea>

Form Events
A form event is fired when a form control receive or loses focus or when the user modify a
form control value such as by typing text in a text input, select any option in a select box etc.
Here're some most important form events and their event handler.

The Focus Event (onfocus)


The focus event occurs when the user gives focus to an element on a web page.

You can handle the focus event with the onfocus event handler. The following example will
highlight the background of text input in yellow color when it receives the focus.

Example
Try this code »
<script>
function highlightInput(elm){
elm.style.background = "yellow";
}
</script>
<input type="text" onfocus="highlightInput(this)">
<button type="button">Button</button>
Note: The value of this keyword inside an event handler refers to the element which has the
handler on it (i.e. where the event is currently being delivered).

The Blur Event (onblur)


The blur event occurs when the user takes the focus away from a form element or a window.

You can handle the blur event with the onblur event handler. The following example will show
you an alert message when the text input element loses focus.

Example
Try this code »
<input type="text" onblur="alert('Text input loses focus!')">
<button type="button">Submit</button>
To take the focus away from a form element first click inside of it then press the tab key on
the keyboard, give focus on something else, or click outside of it.

The Change Event (onchange)


The change event occurs when a user changes the value of a form element.

You can handle the change event with the onchange event handler. The following example will
show you an alert message when you change the option in the select box.

Example
Try this code »
<select onchange="alert('You have changed the selection!');">
<option>Select</option>
<option>Male</option>
<option>Female</option>
</select>

The Submit Event (onsubmit)


The submit event only occurs when the user submits a form on a web page.

You can handle the submit event with the onsubmit event handler. The following example will
show you an alert message while submitting the form to the server.

Example
Try this code »
<form action="action.php" method="post" onsubmit="alert('Form data will be
submitted to the server!');">
<label>First Name:</label>
<input type="text" name="first-name" required>
<input type="submit" value="Submit">
</form>

Document/Window Events
Events are also triggered in situations when the page has loaded or when user resize the
browser window, etc. Here're some most important document/window events and their event
handler.

The Load Event (onload)


The load event occurs when a web page has finished loading in the web browser.

You can handle the load event with the onload event handler. The following example will show
you an alert message as soon as the page finishes loading.

Example
Try this code »
<body onload="window.alert('Page is loaded successfully!');">
<h1>This is a heading</h1>
<p>This is paragraph of text.</p>
</body>

The Unload Event (onunload)


The unload event occurs when a user leaves the current web page.

You can handle the unload event with the onunload event handler. The following example will
show you an alert message when you try to leave the page.

Example
Try this code »
<body onunload="alert('Are you sure you want to leave this page?');">
<h1>This is a heading</h1>
<p>This is paragraph of text.</p>
</body>
The Resize Event (onresize)
The resize event occurs when a user resizes the browser window. The resize event also occurs
in situations when the browser window is minimized or maximized.

You can handle the resize event with the onresize event handler. The following example will
show you an alert message when you resize the browser window to a new width and height.

Example
Try this code »
<p id="result"></p>
<script>
function displayWindowSize() {
var w = window.outerWidth;
var h = window.outerHeight;
var txt = "Window size: width=" + w + ", height=" + h;
document.getElementById("result").innerHTML = txt;
}
window.onresize = displayWindowSize;
</script>

JavaScript Strings. What is String in JavaScript


A string is a sequence of letters, numbers, special characters and arithmetic values or
combination of all. Strings can be created by enclosing the string literal (i.e. string characters)
either within single quotes (') or double quotes ("), as shown in the example below:

Example
Try this code »
var myString = 'Hello World!'; // Single quoted string
var myString = "Hello World!"; // Double quoted string
You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:

Example
Try this code »
var str1 = "it's okay";
var str2 = 'He said "Goodbye"';
var str3 = "She replied 'Calm down, please'";
var str4 = 'Hi, there!"; // Syntax error - quotes must match
However, you can still use single quotes inside a single quoted strings or double quotes inside
double quoted strings by escaping the quotes with a backslash character ( \), like this:
Example
Try this code »
var str1 = 'it\'s okay';
var str2 = "He said \"Goodbye\"";
var str3 = 'She replied \'Calm down, please\'';
The backslash (\) is called an escape character, whereas the sequences \' and \" that we've
used in the example above are called escape sequences.

JavaScript Escape Sequences


Escape sequences are also useful for situations where you want to use characters that can't be
typed using a keyboard. Here are some other most commonly used escape sequences.

 \n is replaced by the newline character


 \t is replaced by the tab character
 \r is replaced by the carriage-return character
 \b is replaced by the backspace character
 \\ is replaced by a single backslash (\)

Here's an example to clarify the how escape sequences actually works:

Example
Try this code »
var str1 = "The quick brown fox \n jumps over the lazy dog.";
document.write("<pre>" + str1 + "</pre>"); // Create line break

var str2 = "C:\Users\Downloads";


document.write(str2); // Prints C:UsersDownloads

var str3 = "C:\\Users\\Downloads";


document.write(str3); // Prints C:\Users\Downloads

Performing Operations on Strings


JavaScript provides several properties and methods to perform operations on string values.
Technically, only objects can have properties and methods. But in JavaScript primitive data
types can act like objects when you refer to them with the property access notation (i.e. dot
notation).

JavaScript making it possible by creating a temporary wrapper object for primitive data types.
This process is done automatically by the JavaScript interpreter in the background.
Getting the Length of a String
The length property returns the length of the string, which is the number of characters
contained in the string. This includes the number of special characters as well, such as \t or \n.

Example
Try this code »
var str1 = "This is a paragraph of text.";
document.write(str1.length); // Prints 28

var str2 = "This is a \n paragraph of text.";


document.write(str2.length); // Prints 30, because \n is only one
character
Note: Since length is a property, not a function, so don't use parentheses after it
like str.length(). Instead just write str.length, otherwise it will produce an error.

Finding a String Inside Another String


You can use the indexOf() method to find a substring or string within another string. This
method returns the index or position of the first occurrence of a specified string within a
string.

Example
Try this code »
var str = "If the facts don't fit the theory, change the facts.";
var pos = str.indexOf("facts");
alert(pos); // 0utputs: 7
Similarly, you can use the lastIndexOf() method to get the index or position of the last
occurrence of the specified string within a string, like this:

Example
Try this code »
var str = "If the facts don't fit the theory, change the facts.";
var pos = str.lastIndexOf("facts");
alert(pos); // 0utputs: 46
Both the indexOf(), and the lastIndexOf() methods return -1 if the substring is not found. Both
methods also accept an optional integer parameter which specifies the position within the
string at which to start the search. Here's an example:

Example
Try this code »
var str = "If the facts don't fit the theory, change the facts.";

// Searching forwards
var pos1 = str.indexOf("facts", 20);
alert(pos1); // 0utputs: 46

// Searching backwards
var pos2 = str.lastIndexOf("facts", 20);
alert(pos2); // 0utputs: 7
Note: Characters in a string are indexed from left to right. The index of the first character is 0,
and the index of the last character of a string called myStr is myStr.length - 1.

Searching for a Pattern Inside a String


You can use the search() method to search a particular piece of text or pattern inside a string.

Like indexOf() method the search() method also returns the index of the first match, and
returns -1 if no matches were found, but unlike indexOf() method this method can also take
a regular expression as its argument to provide advanced search capabilities.

Example
Try this code »
var str = "Color red looks brighter than color blue.";

// Case sensitive search


var pos1 = str.search("color");
alert(pos1); // 0utputs: 30

// Case insensitive search using regexp


var pos2 = str.search(/color/i);
alert(pos2); // 0utputs: 0
Note: The search() method does not support global searches; it ignores the g flag or modifier
(i.e. /pattern/g) of its regular expression argument.

You will learn more about regular expressions in the upcoming chapters.

Extracting a Substring from a String


You can use the slice() method to extract a part or substring from a string.

This method takes 2 parameters: start index (index at which to begin extraction), and an
optional end index (index before which to end extraction), like str.slice(startIndex, endIndex).

The following example slices out a portion of a string from position 4 to position 15:
Example
Try this code »
var str = "The quick brown fox jumps over the lazy dog.";
var subStr = str.slice(4, 15);
document.write(subStr); // Prints: quick brown
You can also specify negative values. The negative value is treated as strLength + startIndex,
where strLength is the length of the string (i.e. str.length), for example, if startIndex is -5 it is
treated as strLength - 5. If startIndex is greater than or equal to the length of the
string, slice() method returns an empty string. Also, if optional endIndex is not specified or
omitted, the slice() method extracts to the end of the string.

Example
Try this code »
var str = "The quick brown fox jumps over the lazy dog.";
document.write(str.slice(-28, -19)); // Prints: fox jumps
document.write(str.slice(31)); // Prints: the lazy dog.
You can also use the substring() method to extract a section of the given string based on start
and end indexes, like str.substring(startIndex, endIndex) . The substring() method is very similar
to the slice() method, except few differences:

 If either argument is less than 0 or is NaN, it is treated as 0.


 If either argument is greater than str.length, it is treated as if it were str.length.
 If startIndex is greater than endIndex, then substring() will swap those two arguments;
for example, str.substring(5, 0) == str.substring(0, 5).

The following example will show you how this method actuallty works:

Example
Try this code »
var str = "The quick brown fox jumps over the lazy dog.";
document.write(str.substring(4, 15)); // Prints: quick brown
document.write(str.substring(9, 0)); // Prints: The quick
document.write(str.substring(-28, -19)); // Prints nothing
document.write(str.substring(31)); // Prints: the lazy dog.

Extracting a Fixed Number of Characters from a String


JavaScript also provide the substr() method which is similar to slice() with a subtle difference,
the second parameter specifies the number of characters to extract instead of ending index,
like str.substr(startIndex, length). If length is 0 or a negative number, an empty string is
returned. The following example demonstrates how it works:
Example
Try this code »
var str = "The quick brown fox jumps over the lazy dog.";
document.write(str.substr(4, 15)); // Prints: quick brown fox
document.write(str.substr(-28, -19)); // Prints nothing
document.write(str.substr(-28, 9)); // Prints: fox jumps
document.write(str.substr(31)); // Prints: the lazy dog.

Replacing the Contents of a String


You can use the replace() method to replace part of a string with another string. This method
takes two parameters a regular expression to match or substring to be replaced and a
replacement string, like str.replace(regexp|substr, newSubstr).

This replace() method returns a new string, it doesn't affect the original string that will remain
unchanged. The following example will show you how it works:

Example
Try this code »
var str = "Color red looks brighter than color blue.";
var result = str.replace("color", "paint");
alert(result); // 0utputs: Color red looks brighter than paint blue.
By default, the replace() method replaces only the first match, and it is case-sensitive. To
replace the substring within a string in a case-insensitive manner you can use a regular
expression (regexp) with an i modifier, as shown in the example below:

Example
Try this code »
var str = "Color red looks brighter than color blue.";
var result = str.replace(/color/i, "paint");
alert(result); // 0utputs: paint red looks brighter than color blue.
Similarly, to replace all the occurrences of a substring within a string in a case-insensitive
manner you can use the g modifier along with the i modifier, like this:

Example
Try this code »
var str = "Color red looks brighter than color blue.";
var result = str.replace(/color/ig, "paint");
alert(result); // 0utputs: paint red looks brighter than paint blue.
Converting a String to Uppercase or Lowercase
You can use the toUpperCase() method to convert a string to uppercase, like this:

Example
Try this code »
var str = "Hello World!";
var result = str.toUpperCase();
document.write(result); // Prints: HELLO WORLD!
Similarly, you can use the toLowerCase() to convert a string to lowercase, like this:

Example
Try this code »
var str = "Hello World!";
var result = str.toLowerCase();
document.write(result); // Prints: hello world!

Concatenating Two or More Strings


You can concatenate or combine two or more strings using the + and += assignment operators.

Example
Try this code »
var hello = "Hello";
var world = "World";
var greet = hello + " " + world;
document.write(greet); // Prints: Hello World

var wish = "Happy";


wish += " New Year";
document.write(wish); // Prints: Happy New Year
JavaScript also provides concat() method to combine strings, but it is not recommended.

Accessing Individual Characters from a String


You can use the charAt() method to access individual character from a string,
like str.charAt(index). The index specified should be an integer between 0 and str.length - 1. If
no index is provided the first character in the string is returned, since the default is 0.

Example
Try this code »
var str = "Hello World!";
document.write(str.charAt()); // Prints: H
document.write(str.charAt(6)); // Prints: W
document.write(str.charAt(30)); // Prints nothing
document.write(str.charAt(str.length - 1)); // Prints: !
There is even better way to do this. Since ECMAScript 5, strings can be treated like read-only
arrays, and you can access individual characters from a string using square brackets ([])
instead of the charAt() method, as demonstrated in the following example:

Example
Try this code »
var str = "Hello World!";
document.write(str[0]); // Prints: H
document.write(str[6]); // Prints: W
document.write(str[str.length - 1]); // Prints: !
document.write(str[30]); // Prints: undefined
Note: The only difference between accessing the character from a string using
the charAt() and square bracket ([]) is that if no character is found, [] returns undefined,
whereas the charAt() method returns an empty string.

Splitting a String into an Array


The split() method can be used to splits a string into an array of strings, using the
syntax str.split(separator, limit). The seperator argument specifies the string at which each
split should occur, whereas the limit arguments specifies the maximum length of the array.

If separator argument is omitted or not found in the specified string, the entire string is
assigned to the first element of the array. The following example shows how it works:

Example
Try this code »
var fruitsStr = "Apple, Banana, Mango, Orange, Papaya";
var fruitsArr = fruitsStr.split(", ");
document.write(fruitsArr[0]); // Prints: Apple
document.write(fruitsArr[2]); // Prints: Mango
document.write(fruitsArr[fruitsArr.length - 1]); // Prints: Papaya

// Loop through all the elements of the fruits array


for(var i in fruitsArr) {
document.write("<p>" + fruitsArr[i] + "</p>");
}
To split a string into an array of characters, specify an empty string ( "") as a separator.

Example
Try this code »
var str = "INTERSTELLAR";
var strArr = str.split("");
document.write(strArr[0]); // Prints: I
document.write(strArr[1]); // Prints: N
document.write(strArr[strArr.length - 1]); // Prints: R

// Loop through all the elements of the characters array and print them
for(var i in strArr) {
document.write("<br>" + strArr[i]);

JavaScript Numbers. Working with Numbers


JavaScript supports both integer and floating-point numbers that can be represented in
decimal, hexadecimal or octal notation. Unlike other languages, JavaScript does not treat
integer and floating-point numbers differently. All numbers in JavaScript are represented as
floating-point numbers. Here's an example demonstrating the numbers in different formats:

Example
Try this code »
var x = 2; // integer number
var y = 3.14; // floating-point number
var z = 0xff; // hexadecimal number
Extra large numbers can be represented in exponential notation e.g. 6.02e+23 (same as
6.02x1023).

Example
Try this code »
var x = 1.57e4; // same as 15700
var y = 4.25e+6; // same as 4.25e6 or 4250000
var z = 4.25e-6; // same as 0.00000425
Tip: The biggest safe integer in JavaScript is 9007199254740991 (253-1), whereas the smallest safe
integer is -9007199254740991 (-(253-1)).

Numbers can also be represented in hexadecimal notation (base 16). Hexadecimal numbers
are prefixed with 0x. They are commonly used to represent colors. Here's an example:

Example
Try this code »
var x = 0xff; // same as 255
var y = 0xb4; // same as 180
var z = 0x00; // same as 0
Note: Integers can be represented in decimal, hexadecimal, and octal notation. Floating-point
numbers can be represented in decimal or exponential notation.
Operating on Numbers and Strings
As you know from the previous chapters, the + operator is used for both addition and
concatenation. So, performing mathematical operations on numbers and strings may produce
interesting results. The following example will show you what happens when you add
numbers and strings:

Example
Try this code »
var x = 10;
var y = 20;
var z = "30";

// Adding a number with a number, the result will be sum of numbers


console.log(x + y); // 30

// Adding a string with a string, the result will be string concatenation


console.log(z + z); // '3030'

// Adding a number with a string, the result will be string concatenation


console.log(x + z); // '1030'

// Adding a string with a number, the result will be string concatenation


console.log(z + x); // '3010'

// Adding strings and numbers, the result will be string concatenation


console.log("The result is: " + x + y); // 'The result is: 1020'

// Adding numbers and strings, calculation performed from left to right


console.log(x + y + z); // 'The result is: 3030'
If you observe the above example carefully, you will find that the result of the last operation is
not just a simple string concatenation, because operators with the same precedence are
evaluated from left to right. That's why, since variables x and y both are numbers they are
added first then the result is concatenated with the variable z which is a string, hence final
result is 30 + "30" = "3030".

But, if you perform other mathematical operations like multiplication, division, or subtraction
the result will be different. JavaScript will automatically convert numeric strings (i.e. strings
containing numeric values) to numbers in all numeric operations, as shown in the following
example:

Example
Try this code »
var x = 10;
var y = 20;
var z = "30";

// Subtracting a number from a number


console.log(y - x); // 10

// Subtracting a number from a numeric string


console.log(z - x); // 20

// Multiplying a number with a numeric string


console.log(x * z); // 300

// Dividing a number with a numeric string


console.log(z / x); // 3
Moreover, if you try to multiply or divide numbers with strings that are not numeric, it
returns NaN (Not a Number). Also, if you use NaN in a mathematical operation, the result will
also be NaN.

Example
Try this code »
var x = 10;
var y = "foo";
var z = NaN;

// Subtracting a number from a non-numeric string


console.log(y - x); // NaN

// Multiplying a number with a non-numeric string


console.log(x * y); // NaN

// Dividing a number with a non-numeric string


console.log(x / y); // NaN

// Adding NaN to a number


console.log(x + z); // NaN

// Adding NaN to a string


console.log(y + z); // fooNaN

Representing Infinity
Infinity represents a number too big for JavaScript to handle. JavaScript has special
keyword Infinity and -Infinity to represent positive and negative infinity respectively. For
example, dividing by 0 returns Infinity, as demonstrated below:

Example
Try this code »
var x = 5 / 0;
console.log(x); // Infinity

var y = -5 / 0;
console.log(y); // -Infinity
Note: Infinity is a special value that represents the mathematical Infinity ∞, which is greater
than any number. The typeof operator return number for an Infinity value.

Avoiding Precision Problems


Sometimes, operations on floating-point numbers produce unexpected results, as shown
here:

Example
Try this code »
var x = 0.1 + 0.2;
console.log(x) // 0.30000000000000004
As you can see the result is 0.30000000000000004 rather than the expected 0.3. This difference is
called representation error or roundoff error. It occurs because JavaScript and many other
languages uses binary (base 2) form to represent decimal (base 10) numbers internally.
Unfortunately, most decimal fractions can't be represented exactly in binary form, so small
differences occur.

To avoid this problem you can use the solution something like this:

Example
Try this code »
var x = (0.1 * 10 + 0.2 * 10) / 10;
console.log(x) // 0.3
JavaScript round floating-point numbers to 17 digits, which is enough precision or accuracy in
most cases. Also, in JavaScript integers (numbers without fractional parts or exponential
notation) are accurate is up to 15 digits, as demonstrated in the following example:

Example
Try this code »
var x = 999999999999999;
console.log(x); // 999999999999999

var y = 9999999999999999;
console.log(y); // 10000000000000000
Performing Operations on Numbers
JavaScript provides several properties and methods to perform operations on number values.
As you already know from the previous chapters, in JavaScript primitive data types can act like
objects when you refer to them with the property access notation (i.e. dot notation).

In the following sections, we will look at the number methods that are most commonly used.

Parsing Integers from Strings


The parseInt() method can be used to parse an integer from a string. This method is
particularly handy in situations when you are dealing with the values like CSS units
e.g. 50px, 12pt, etc. and you would like to extract the numeric value out of it.

If the parseInt() method encounters a character that is not numeric in the specified base, it
stops parsing and returns the integer value parsed up to that point. If the first character
cannot be converted into a number, the method will return NaN (not a number).

Leading and trailing spaces are allowed. Here's an example:

Example
Try this code »
console.log(parseInt("3.14")); // 3
console.log(parseInt("50px")); // 50
console.log(parseInt("12pt")); // 12
console.log(parseInt("0xFF", 16)); // 255
console.log(parseInt("20 years")); // 20
console.log(parseInt("Year 2048")); // NaN
console.log(parseInt("10 12 2018")); // 10
Note: The parseInt() method truncates numbers to integer values, but it should not be used
as a substitute for Math.floor() method.
Similarly, you can use the parseFloat() method to parse floating-point number from a string.
The parseFloat() method works the same way as the parseInt() method, except that it retrieves
both integers and numbers with decimals.

Example
Try this code »
console.log(parseFloat("3.14")); // 3.14
console.log(parseFloat("50px")); // 50
console.log(parseFloat("1.6em")); // 1.6
console.log(parseFloat("124.5 lbs")); // 124.5
console.log(parseFloat("weight 124.5 lbs")); // NaN
console.log(parseFloat("6.5 acres")); // 6.5
Converting Numbers to Strings
The toString() method can be used to convert a number to its string equivalent. This method
optionally accepts an integer parameter in the range 2 through 36 specifying the base to use
for representing numeric values. Here's an example:

Example
Try this code »
var x = 10;
var y = x.toString();
console.log(y); // '10'
console.log(typeof y); // string
console.log(typeof x); // number

console.log((12).toString()); // '12'
console.log((15.6).toString()); // '15.6'
console.log((6).toString(2)); // '110'
console.log((255).toString(16)); // 'ff'

Formatting Numbers in Exponential Notation


You can use the toExponential() method to format or represent a number in exponential
notation. This method optionally accepts an integer parameter specifying the number of digits
after the decimal point. Also, the returned value is a string not a number. Here's an example:

Example
Try this code »
var x = 67.1234;

console.log(x.toExponential()); // 6.71234e+1
console.log(x.toExponential(6)); // 6.712340e+1
console.log(x.toExponential(4)); // 6.7123e+1
console.log(x.toExponential(2)); // 6.71e+1
Note: Exponential notation is useful for representing numbers that are either very large or
very small in magnitude. For example, 62500000000 can be written as 625e+8 or 6.25e+10.

Formatting Numbers to Fixed Decimals


You can use the toFixed() method when you want to format a number with a fixed number of
digits to the right of the decimal point. The value returned by this method is a string and it
has exactly specified number of digits after the decimal point. If the digits parameter is not
specified or omitted, it is treated as 0. Here's an example:
Example
Try this code »
var x = 72.635;

console.log(x.toFixed()); // '73' (note rounding, no fractional part)


console.log(x.toFixed(2)); // '72.64' (note rounding)
console.log(x.toFixed(1)); // '72.6'

var y = 6.25e+5;
console.log(y.toFixed(2)); // '625000.00'

var z = 1.58e-4;
console.log(z.toFixed(2)); // '0.00' (since 1.58e-4 is equal to 0.000158)

Formatting Numbers with Precision


If you want most appropriate form of a number, you can use the toPrecision() method instead.
This method returns a string representing the number to the specified precision.

If precision is large enough to include all the digits of the integer part of number, then the
number is formatted using fixed-point notation. Otherwise, the number is formatted using
exponential notation. The precision parameter is optional. Here's an example:

Example
Try this code »
var x = 6.235;

console.log(x.toPrecision()); // '6.235'
console.log(x.toPrecision(3)); // '6.24' (note rounding)
console.log(x.toPrecision(2)); // '6.2'
console.log(x.toPrecision(1)); // '6'

var y = 47.63;
console.log(y.toPrecision(2)); // '48' (note rounding, no fractional part)

var z = 1234.5;
console.log(z.toPrecision(2)); // '1.2e+3'

Finding the Largest and Smallest Possible Numbers


The Number object also has several properties associated with it.
The Number.MAX_VALUE and Number.MIN_VALUE properties of the Number object represent the
largest and smallest (closest to zero, not most negative) possible positive numbers that
JavaScript can handle. They are constants and their actual values are 1.7976931348623157e+308,
and 5e-324, respectively.
A number that falls outside of the range of possible numbers is represented by a
constant Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY. Here's an example:

Example
Try this code »
var a = Number.MAX_VALUE;
console.log(a); // 1.7976931348623157e+308

var b = Number.MIN_VALUE;
console.log(b); // 5e-324

var x = Number.MAX_VALUE * 2;
console.log(x); // Infinity

var y = -1 * Number.MAX_VALUE * 2;
console.log(y); // -Infinity

JavaScript If…Else Statements


JavaScript Conditional Statements
Like many other programming languages, JavaScript also allows you to write code that
perform different actions based on the results of a logical or comparative test conditions at
run time. This means, you can create test conditions in the form of expressions that evaluates
to either true or false and based on these results you can perform certain actions.

There are several conditional statements in JavaScript that you can use to make decisions:

 The if statement
 The if...else statement
 The if...else if....else statement
 The switch...case statement

We will discuss each of these statements in detail in the coming sections.

The if Statement
The if statement is used to execute a block of code only if the specified condition evaluates to
true. This is the simplest JavaScript's conditional statements and can be written like:

if(condition) {
// Code to be executed
}
The following example will output "Have a nice weekend!" if the current day is Friday:

Example
Try this code »
var now = new Date();
var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

if(dayOfWeek == 5) {
alert("Have a nice weekend!");
}

The if...else Statement


You can enhance the decision making capabilities of your JavaScript program by providing an
alternative choice through adding an else statement to the if statement.

The if...else statement allows you to execute one block of code if the specified condition is
evaluates to true and another block of code if it is evaluates to false. It can be written, like this:

if(condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}

The JavaScript code in the following example will output "Have a nice weekend!" if the current
day is Friday, otherwise it will output the text "Have a nice day!".

Example
Try this code »
var now = new Date();
var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else {
alert("Have a nice day!");
}

The if...else if...else Statement


The if...else if...else a special statement that is used to combine multiple if...else statements.

if(condition1) {
// Code to be executed if condition1 is true
} else if(condition2) {
// Code to be executed if the condition1 is false and condition2 is true
} else {
// Code to be executed if both condition1 and condition2 are false
}

The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday, otherwise it will output "Have a nice day!"

Example
Try this code »
var now = new Date();
var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else if(dayOfWeek == 0) {
alert("Have a nice Sunday!");
} else {
alert("Have a nice day!");
}
You will learn about the JavaScript switch-case statement in the next chapter.

The Ternary Operator


The ternary operator provides a shorthand way of writing the if...else statements. The ternary
operator is represented by the question mark (?) symbol and it takes three operands: a
condition to check, a result for true, and a result for false. Its basic syntax is:
var result = (condition) ? value1 : value2

If the condition is evaluated to true the value1 will be returned, otherwise value2 will be
returned. To understand how this operator works, consider the following examples:

Example
Try this code »
var userType;
var age = 21;
if(age < 18) {
userType = 'Child';
} else {
userType = 'Adult';
}
alert(userType); // Displays Adult
Using the ternary operator the same code could be written in a more compact way:
Example
Try this code »
var age = 21;
var userType = age < 18 ? 'Child' : 'Adult';
alert(userType); // Displays Adult
As you can see in the above example, since the specified condition evaluated to false the
value on the right side of the colon (:) is returned, which is the string 'Adult'.

Tip: Code written using the ternary operator can be difficult to read sometimes. However, it
provides a great way to write compact if-else statements.

JavaScript Switch...Case Statements


Using the Switch...Case Statement
The switch..case statement is an alternative to the if...else if...else statement, which does almost
the same thing. The switch...case statement tests a variable or expression against a series of
values until it finds a match, and then executes the block of code corresponding to that
match. It's syntax is:

switch(x){
case value1:
// Code to be executed if x === value1
break;
case value2:
// Code to be executed if x === value2
break;
...
default:
// Code to be executed if x is different from all values
}

Consider the following example, which display the name of the day of the week.

Example
Try this code »
var d = new Date();

switch(d.getDay()) {
case 0:
alert("Today is Sunday.");
break;
case 1:
alert("Today is Monday.");
break;
case 2:
alert("Today is Tuesday.");
break;
case 3:
alert("Today is Wednesday.");
break;
case 4:
alert("Today is Thursday.");
break;
case 5:
alert("Today is Friday.");
break;
case 6:
alert("Today is Saturday.");
break;
default:
alert("No information available for that day.");
break;
}
The getDay() method returns the weekday as a number from 0 and 6, where 0 represents
Sunday. See the JavaScript date and time chapter to learn more about date methods.

Note: In a switch...case statement, the value of the expression or variable is compared against
the case value using the strict equality operator (===). That means if x = "0", it doesn't
match case 0:, because their data types are not equal.

The switch...case statement differs from the if...else statement in one important way. The switch
statement executes line by line (i.e. statement by statement) and once JavaScript finds
a case clause that evaluates to true, it's not only executes the code corresponding to that case
clause, but also executes all the subsequent case clauses till the end of the switch block
automatically. To prevent this you must include a break statement after each case (as you can
see in the above example). The break statement tells the JavaScript interpreter to break out of
the switch...case statement block once it executes the code associated with the first true case.

The break statement is however not required for the case or default clause, when it appears at
last in a switch statement. Though, it a good programming practice to terminate the last case,
or default clause in a switch statement with a break. It prevents a possible programming error
later if another case statement is added to the switch statement. The default clause is optional,
which specify actions to be performed if no case matches the switch expression.
The default clause does not have to be the last clause to appear in a switch statement. Here's
an example, where default is not the last clause.

Example
Try this code »
var d = new Date();
switch(d.getDay()) {
default:
alert("Looking forward to the weekend.");
break;
case 6:
alert("Today is Saturday.");
break;
case 0:
alert("Today is Sunday.");
}

Multiple Cases Sharing Same Action


Each case value must be unique within a switch statement. However, different cases don't
need to have a unique action. Several cases can share the same action, as shown here:

Example
Try this code »
var d = new Date();

switch(d.getDay()) {
case 1:
case 2:
case 3:
case 4:
case 5:
alert("It is a weekday.");
break;
case 0:
case 6:
alert("It is a weekend day.");
break;
default:
alert("Enjoy every day of your life.");
}

JavaScript Arrays. What is an Array


Arrays are complex variables that allow us to store more than one value or a group of values
under a single variable name. JavaScript arrays can store any valid value, including strings,
numbers, objects, functions, and even other arrays, thus making it possible to create more
complex data structures such as an array of objects or an array of arrays. Let's suppose you
want to store the name of colors in your JavaScript code. Storing the color names one by one
in a variable could look something like this:
Example
Try this code »
var color1 = "Red";
var color2 = "Green";
var color3 = "Blue";
But what happens if you need to store the state or city names of a country in variables and
this time this not just three may be hundred. It is quite hard and boring to store each of them
in a separate variable. Also, using so many variables simultaneously and keeping track of them
all will be a very difficult task. And here array comes into play. Arrays solve this problem by
providing an ordered structure for storing multiple values or a group of values.

Creating an Array
The simplest way to create an array in JavaScript is enclosing a comma-separated list of values
in square brackets ([]), as shown in the following syntax:
var myArray = [element0, element1, ..., elementN];

Array can also be created using the Array() constructor as shown in the following syntax.
However, for the sake of simplicity previous syntax is recommended.
var myArray = new Array(element0, element1, ..., elementN);

Here are some examples of arrays created using array literal syntax:

Example
Try this code »
var colors = ["Red", "Green", "Blue"];
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var cities = ["London", "Paris", "New York"];
var person = ["John", "Wick", 32];

Note: An array is an ordered collection of values. Each value in an array is called an element,
and each element has a numeric position in an array, known as its index.

Accessing the Elements of an Array


Array elements can be accessed by their index using the square bracket notation. An index is a
number that represents an element's position in an array.

Array indexes are zero-based. This means that the first item of an array is stored at index 0,
not 1, the second item is stored at index 1, and so on. Array indexes start at 0 and go up to
the number of elements minus 1. So, array of five elements would have indexes from 0 to 4.
The following example will show you how to get individual array element by their index.

Example
Try this code »
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

document.write(fruits[0]); // Prints: Apple


document.write(fruits[1]); // Prints: Banana
document.write(fruits[2]); // Prints: Mango
document.write(fruits[fruits.length - 1]); // Prints: Papaya
Note: In JavaScript, arrays are really just a special type of objects which has numeric indexes
as keys. The typeof operator will return "object" for arrays.

Getting the Length of an Array


The length property returns the length of an array, which is the total number of elements
contained in the array. Array length is always greater than the index of any of its element.

Example
Try this code »
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
document.write(fruits.length); // Prints: 5

Looping Through Array Elements


You can use for loop to access each element of an array in sequential order, like this:

Example
Try this code »
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Iterates over array elements


for(var i = 0; i < fruits.length; i++) {
document.write(fruits[i] + "<br>"); // Print array element
}
ECMAScript 6 has introduced a simpler way to iterate over array element, which is for-of loop.
In this loop you don't have to initialize and keep track of the loop counter variable ( i).

Here's the same example rewritten using the for-of loop:


Example
Try this code »
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Iterates over array elements


for(var fruit of fruits) {
document.write(fruit + "<br>"); // Print array element
}
You can also iterate over the array elements using for-in loop, like this:

Example
Try this code »
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Loop through all the elements in the array


for(var i in fruits) {
document.write(fruits[i] + "<br>");
}
Note: The for-in loop should not be used to iterate over an array where the index order is
important. The for-in loop is optimized for iterating over object's properties, you should
better use a for loop with a numeric index or for-of loop.

Adding New Elements to an Array


To add a new element at the end of an array, simply use the push() method, like this:

Example
Try this code »
var colors = ["Red", "Green", "Blue"];
colors.push("Yellow");

document.write(colors); // Prints: Red,Green,Blue,Yellow


document.write(colors.length); // Prints: 4
Similarly, to add a new element at the beginning of an array use the unshift() method, like
this:

Example
Try this code »
var colors = ["Red", "Green", "Blue"];
colors.unshift("Yellow");

document.write(colors); // Prints: Yellow,Red,Green,Blue


document.write(colors.length); // Prints: 4
You can also add multiple elements at once using the push() and unshift() methods, like this:

Example
Try this code »
var colors = ["Red", "Green", "Blue"];
colors.push("Pink", "Voilet");
colors.unshift("Yellow", "Grey");

document.write(colors); // Prints: Yellow,Grey,Red,Green,Blue,Pink,Voilet


document.write(colors.length); // Prints: 7

Removing Elements from an Array


To remove the last element from an array you can use the pop() method. This method returns
the value that was popped out. Here's an example:

Example
Try this code »
var colors = ["Red", "Green", "Blue"];
var last = colors.pop();

document.write(last); // Prints: Blue


document.write(colors.length); // Prints: 2
Similarly, you can remove the first element from an array using the shift() method. This
method also returns the value that was shifted out. Here's an example:

Example
Try this code »
var colors = ["Red", "Green", "Blue"];
var first = colors.shift();

document.write(first); // Prints: Red


document.write(colors.length); // Prints: 2
Tip: The push() and pop() methods runs faster than unshift() and shift().
Because push() and pop() methods simply add and remove elements at the end of an array
therefore the elements do not move, whereas unshift() and shift() add and remove elements
at the beginning of the array that require re-indexing of whole array.
Adding or Removing Elements at Any Position
The splice() method is a very versatile array method that allows you to add or remove
elements from any index, using the syntax arr.splice(startIndex, deleteCount, elem1, ...,
elemN).

This method takes three parameters: the first parameter is the index at which to start splicing
the array, it is required; the second parameter is the number of elements to remove (use 0 if
you don't want to remove any elements), it is optional; and the third parameter is a set of
replacement elements, it is also optional. The following example shows how it works:

Example
Try this code »
var colors = ["Red", "Green", "Blue"];
var removed = colors.splice(0,1); // Remove the first element

document.write(colors); // Prints: Green,Blue


document.write(removed); // Prints: Red (one item array)
document.write(removed.length); // Prints: 1

removed = colors.splice(1, 0, "Pink", "Yellow"); // Insert two items at


position one
document.write(colors); // Prints: Green,Pink,Yellow,Blue
document.write(removed); // Empty array
document.write(removed.length); // Prints: 0

removed = colors.splice(1, 1, "Purple", "Voilet"); // Insert two values,


remove one
document.write(colors); //Prints: Green,Purple,Voilet,Yellow,Blue
document.write(removed); // Prints: Pink (one item array)
document.write(removed.length); // Prints: 1
The splice() method returns an array of the deleted elements, or an empty array if no
elements were deleted, as you can see in the above example. If the second argument is
omitted, all elements from the start to the end of the array are removed.
Unlike slice() and concat() methods, the splice() method modifies the array on which it is
called on.

Creating a String from an Array


There may be situations where you simply want to create a string by joining the elements of
an array. To do this you can use the join() method. This method takes an optional parameter
which is a separator string that is added in between each element. If you omit the separator,
then JavaScript will use comma (,) by default. The following example shows how it works:
Example
Try this code »
var colors = ["Red", "Green", "Blue"];

document.write(colors.join()); // Prints: Red,Green,Blue


document.write(colors.join("")); // Prints: RedGreenBlue
document.write(colors.join("-")); // Prints: Red-Green-Blue
document.write(colors.join(", ")); // Prints: Red, Green, Blue
You can also convert an array to a comma-separated string using the toString(). This method
does not accept the separator parameter like join(). Here's an example:

Example
Try this code »
var colors = ["Red", "Green", "Blue"];
document.write(colors.toString()); // Prints: Red,Green,Blue

Extracting a Portion of an Array


If you want to extract out a portion of an array (i.e. subarray) but keep the original array intact
you can use the slice() method. This method takes 2 parameters: start index (index at which
to begin extraction), and an optional end index (index before which to end extraction),
like arr.slice(startIndex, endIndex). Here's an example:

Example
Try this code »
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var subarr = fruits.slice(1, 3);
document.write(subarr); // Prints: Banana,Mango
If endIndex parameter is omitted, all elements to the end of the array are extracted. You can
also specify negative indexes or offsets —in that case the slice() method extract the elements
from the end of an array, rather then the begining. For example:

Example
Try this code »
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

document.write(fruits.slice(2)); // Prints: Mango,Orange,Papaya


document.write(fruits.slice(-2)); // Prints: Orange,Papaya
document.write(fruits.slice(2, -1)); // Prints: Mango,Orange
Merging Two or More Arrays
The concat() method can be used to merge or combine two or more arrays. This method does
not change the existing arrays, instead it returns a new array. For example:

Example
Try this code »
var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"];

// Creating new array by combining pets and wilds arrays


var animals = pets.concat(wilds);
document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra
The concat() method can take any number of array arguments, so you can create an array
from any number of other arrays, as shown in the following example:

Example
Try this code »
var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"];
var bugs = ["Ant", "Bee"];

// Creating new array by combining pets, wilds and bugs arrays


var animals = pets.concat(wilds, bugs);
document.write(animals); // Prints:
Cat,Dog,Parrot,Tiger,Wolf,Zebra,Ant,Bee

Searching Through an Array


If you want to search an array for a specific value, you can simply use
the indexOf() and lastIndexOf(). If the value is found, both methods return an index
representing the array element. If the value is not found, -1 is returned. The indexOf() method
returns the first one found, whereas the lastIndexOf() returns the last one found.

Example
Try this code »
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

document.write(fruits.indexOf("Apple")); // Prints: 0
document.write(fruits.indexOf("Banana")); // Prints: 1
document.write(fruits.indexOf("Pineapple")); // Prints: -1
Both methods also accept an optional integer parameter from index which specifies the index
within the array at which to start the search. Here's an example:
Example
Try this code »
var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

// Searching forwards, starting at from- index


document.write(arr.indexOf(1, 2)); // Prints: 3

// Searching backwards, starting at from index


document.write(arr.lastIndexOf(1, 2)); // Prints: 0
You can also use includes() method to find out whether an array includes a certain element or
not. This method takes the same parameters as indexOf() and lastIndexOf() methods, but it
returns true or false instead of index number. For example:

Example
Try this code »
var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

document.write(arr.includes(1)); // Prints: true


document.write(arr.includes(6)); // Prints: false
document.write(arr.includes(1, 2)); // Prints: true
document.write(arr.includes(3, 4)); // Prints: false
If you want to search an array based on certain condition then you can use the
JavaScript find() method which is newly introduced in ES6. This method returns the value of
the first element in the array that satisfies the provided testing function. Otherwise it
return undefined.

Example
Try this code »
var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

var result = arr.find(function(element) {


return element > 4;
});
document.write(result); // Prints: 5
There is one more method similar to find() is findIndex() method, which returns the index of a
found element in the array instead of its value. For example:

Example
Try this code »
var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

var result = arr.findIndex(function(element) {


return element > 6;
});
document.write(result); // Prints: 8
The find() method only looks for the first element that satisfies the provided testing function.
However, if you want to find out all the matched elements you can use the filter() method.

The filter() method creates a new array with all the elements that successfully passes the
given test. The following example will show you how this actually works:

Example
Try this code »
var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

var result = arr.filter(function(element) {


return element > 4;
});
document.write(result); // Prints: 5,7
document.write(result.length); // Prints: 2

JavaScript Sorting Arrays. Sorting an Array


Sorting is a common task when working with arrays. It would be used, for instance, if you want
to display the city or county names in alphabetical order.

The JavaScript Array object has a built-in method sort() for sorting array elements in
alphabetical order. The following example demonstrates how it works:

Example
Try this code »
var fruits = ["Banana", "Orange", "Apple", "Papaya", "Mango"];
var sorted = fruits.sort();

alert(fruits); // Outputs: Apple,Banana,Mango,Orange,Papaya


alert(sorted); // Outputs: Apple,Banana,Mango,Orange,Papaya

Reversing an Array
You can use the reverse() method to reverse the order of the elements of an array.

This method reverses an array in such a way that the first array element becomes the last, and
the last array element becomes the first. Here's an example:

Example
Try this code »
var counts = ["one", "two", "three", "four", "five"];
var reversed = counts.reverse();

alert(counts); // Outputs: five,four,three,two,one


alert(reversed); // Output: five,four,three,two,one
Note: The sort() and reverse() method modifies the original array and return a reference to
the same array, as you can see in the above examples.

Sorting Numeric Arrays


The sort() method may produce unexpected result when it is applied on the numeric arrays
(i.e. arrays containing numeric values). For instance:

Example
Try this code »
var numbers = [5, 20, 10, 75, 50, 100];
numbers.sort(); // Sorts numbers array
alert(numbers); // Outputs: 10,100,20,5,50,75
As you can see, the result is different from what we've expected. It happens because,
the sort() method sorts the numeric array elements by converting them to strings (i.e. 20
becomes "20", 100 becomes "100", and so on), and since the first character of string "20" (i.e.
"2") comes after the first character of string "100" (i.e. "1"), that's why the value 20 is sorted
after the 100.

To fix this sorting problem with numeric array, you can pass a compare function, like this:

Example
Try this code »
var numbers = [5, 20, 10, 75, 50, 100];

// Sorting an array using compare function


numbers.sort(function(a, b) {
return a - b;
});
alert(numbers); // Outputs: 5,10,20,50,75,100
As you can see, this time we've got the correct result. Let's see how it works.

When compare function is specified, array elements are sorted according to the return value
of the compare function. For example, when comparing a and b:

 If the compare function returns a value less than 0, then a comes first.
 If the compare function returns a value greater than 0, then b comes first.
 If the compare function returns 0, a and b remain unchanged with respect to each other,
but sorted with respect to all other elements.
Hence, since 5 - 20 = -15 which is less than 0, therefore 5 comes first, similarly 20 - 10 =
10 which is greater than 0, therefore 10 comes before 20, likewise 20 - 75 = -55 which is less
than 0, so 20 comes before 75, similarly 50 comes before 75, and so on.

Find Maximum and Minimum Value in an Array


You can use the apply() method in combination with the Math.max() and Math.min() to find the
maximum and minimum value inside an array, like this:

Example
Try this code »
var numbers = [3, -7, 10, 8, 15, 2];

// Defining function to find maximum value


function findMax(array) {
return Math.max.apply(null, array);
}

// Defining function to find minimum value


function findMin(array) {
return Math.min.apply(null, array);
}

alert(findMax(numbers)); // Outputs: 15
alert(findMin(numbers)); // Outputs: -7
The apply() method provides a convenient way to pass array values as arguments to a
function that accepts multiple arguments in an array-like manner, but not an array
(e.g. Math.max() and Math.min() methods here). So, the resulting statement Math.max.apply(null,
numbers) in the example above is equivalent to the Math.max(3, -7, 10, 8, 15, 2).

Sorting an Array of Objects


The sort() method can also be used for sorting object arrays using the compare function.

The following example will show you how to sort an array of objects by property values:

Example
Try this code »
var persons = [
{ name: "Harry", age: 14 },
{ name: "Ethan", age: 30 },
{ name: "Peter", age: 21 },
{ name: "Clark", age: 42 },
{ name: "Alice", age: 16 }
];
// Sort by age
persons.sort(function (a, b) {
return a.age - b.age;
});

console.log(persons);

// Sort by name
persons.sort(function(a, b) {
var x = a.name.toLowerCase(); // ignore upper and lowercase
var y = b.name.toLowerCase(); // ignore upper and lowercase
if(x < y) {
return -1;
}
if(x > y) {
return 1;
}
// names must be equal
return 0;
});

console.log(persons);

JavaScript Loops
Different Types of Loops in JavaScript
Loops are used to execute the same block of code again and again, as long as a certain
condition is met. The basic idea behind a loop is to automate the repetitive tasks within a
program to save the time and effort. JavaScript now supports five different types of loops:

 while — loops thru a block of code as long as the condition specified evaluates to true.
 do…while — loops through a block of code once; then the condition is evaluated. If the
condition is true, the statement is repeated as long as the specified condition is true.
 for — loops through a block of code until the counter reaches a specified number.
 for…in — loops through the properties of an object.
 for…of — loops over iterable objects such as arrays, strings, etc.

In the following sections, we will discuss each of these loop statements in detail.

The while Loop


This is the simplest looping statement provided by JavaScript.
The while loop loops through a block of code as long as the specified condition evaluates to
true. As soon as the condition fails, the loop is stopped. The generic syntax of the while loop
is:
while(condition) {
// Code to be executed
}

The following example defines a loop that will continue to run as long as the variable i is less
than or equal to 5. The variable i will increase by 1 each time the loop runs:

Example
Try this code »
var i = 1;
while(i <= 5) {
document.write("<p>The number is " + i + "</p>");
i++;
}
Note: Make sure that the condition specified in your loop eventually goes false. Otherwise,
the loop will never stop iterating which is known as infinite loop. A common mistake is to
forget to increment the counter variable (variable i in our case).

The do...while Loop


The do-while loop is a variant of the while loop, which evaluates the condition at the end of
each loop iteration. With a do-while loop the block of code executed once, and then the
condition is evaluated, if the condition is true, the statement is repeated as long as the
specified condition evaluated to is true. The generic syntax of the do-while loop is:
do {
// Code to be executed
}
while(condition);

The JavaScript code in the following example defines a loop that starts with i=1. It will then
print the output and increase the value of variable i by 1. After that the condition is evaluated,
and the loop will continue to run as long as the variable i is less than, or equal to 5.

Example
Try this code »
var i = 1;
do {
document.write("<p>The number is " + i + "</p>");
i++;
}
while(i <= 5);
Difference Between while and do...while Loop
The while loop differs from the do-while loop in one important way — with a while loop, the
condition to be evaluated is tested at the beginning of each loop iteration, so if the
conditional expression evaluates to false, the loop will never be executed.

With a do-while loop, on the other hand, the loop will always be executed once even if the
conditional expression evaluates to false, because unlike the while loop, the condition is
evaluated at the end of the loop iteration rather than the beginning.

The for Loop


The for loop repeats a block of code as long as a certain condition is met. It is typically used
to execute a block of code for certain number of times. Its syntax is:
for(initialization; condition; increment) {
// Code to be executed
}

The parameters of the for loop statement have following meanings:

 initialization — it is used to initialize the counter variables, and evaluated once


unconditionally before the first execution of the body of the loop.
 condition — it is evaluated at the beginning of each iteration. If it evaluates to true, the
loop statements execute. If it evaluates to false, the execution of the loop ends.
 increment — it updates the loop counter with a new value each time the loop runs.

The following example defines a loop that starts with i=1. The loop will continued until the
value of variable i is less than or equal to 5. The variable i will increase by 1 each time the
loop runs:

Example
Try this code »
for(var i=1; i<=5; i++) {
document.write("<p>The number is " + i + "</p>");
}
The for loop is particularly useful for iterating over an array. The following example will show
you how to print each item or element of the JavaScript array.

Example
Try this code »
// An array with some elements
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
// Loop through all the elements in the array
for(var i=0; i<fruits.length; i++) {
document.write("<p>" + fruits[i] + "</p>");
}

The for...in Loop


The for-in loop is a special type of a loop that iterates over the properties of an object, or the
elements of an array. The generic syntax of the for-in loop is:
for(variable in object) {
// Code to be executed
}

The loop counter i.e. variable in the for-in loop is a string, not a number. It contains the name
of current property or the index of the current array element.

The following example will show you how to loop through all properties of a JavaScript object.

Example
Try this code »
// An object with some properties
var person = {"name": "Clark", "surname": "Kent", "age": "36"};

// Loop through all the properties in the object


for(var prop in person) {
document.write("<p>" + prop + " = " + person[prop] + "</p>");
}
Similarly, you can loop through the elements of an array, like this:

Example
Try this code »
// An array with some elements
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Loop through all the elements in the array


for(var i in fruits) {
document.write("<p>" + fruits[i] + "</p>");
}
Note: The for-in loop should not be used to iterate over an array where the index order is
important. You should better use a for loop with a numeric index.
The for...of Loop
ES6 introduces a new for-of loop which allows us to iterate over arrays or other iterable
objects (e.g. strings) very easily. Also, the code inside the loop is executed for each element of
the iterable object.

The following example will show you how to loop through arrays and strings using this loop.

Example
Try this code »
// Iterating over array
let letters = ["a", "b", "c", "d", "e", "f"];

for(let letter of letters) {


console.log(letter); // a,b,c,d,e,f
}

// Iterating over string


let greet = "Hello World!";

for(let character of greet) {


console.log(character); // H,e,l,l,o, ,W,o,r,l,d,!
}
To learn about other ES6 features, please check out the JavaScript ES6 features chapter.

Note: The for...of loop doesn't work with objects because they are not iterable. If you want
to iterate over the properties of an object you can use the for-in loop.

JavaScript Functions. What is Function?


A function is a group of statements that perform specific tasks and can be kept and
maintained separately form main program. Functions provide a way to create reusable code
packages which are more portable and easier to debug. Here are some advantages of using
functions:

 Functions reduces the repetition of code within a program — Function allows you to
extract commonly used block of code into a single component. Now you can perform the
same task by calling this function wherever you want within your script without having to
copy and paste the same block of code again and again.
 Functions makes the code much easier to maintain — Since a function created once can
be used many times, so any changes made inside a function automatically implemented at
all the places without touching the several files.
 Functions makes it easier to eliminate the errors — When the program is subdivided
into functions, if any error occur you know exactly what function causing the error and
where to find it. Therefore, fixing errors becomes much easier.

The following section will show you how to define and call functions in your scripts.

Defining and Calling a Function


The declaration of a function start with the function keyword, followed by the name of the
function you want to create, followed by parentheses i.e. () and finally place your function's
code between curly brackets {}. Here's the basic syntax for declaring a function:
function functionName() {
// Code to be executed
}

Here is a simple example of a function, that will show a hello message:

Example
Try this code »
// Defining function
function sayHello() {
alert("Hello, welcome to this website!");
}

// Calling function
sayHello(); // 0utputs: Hello, welcome to this website!
Once a function is defined it can be called (invoked) from anywhere in the document, by
typing its name followed by a set of parentheses, like sayHello() in the example above.

Note: A function name must start with a letter or underscore character not with a number,
optionally followed by the more letters, numbers, or underscore characters. Function names
are case sensitive, just like variable names.

Adding Parameters to Functions


You can specify parameters when you define your function to accept input values at run time.
The parameters work like placeholder variables within a function; they're replaced at run time
by the values (known as argument) provided to the function at the time of invocation.

Parameters are set on the first line of the function inside the set of parentheses, like this:
function functionName(parameter1, parameter2, parameter3) {
// Code to be executed
}
The displaySum() function in the following example takes two numbers as arguments, simply
add them together and then display the result in the browser.

Example
Try this code »
// Defining function
function displaySum(num1, num2) {
var total = num1 + num2;
alert(total);
}

// Calling function
displaySum(6, 20); // 0utputs: 26
displaySum(-5, 17); // 0utputs: 12
You can define as many parameters as you like. However for each parameter you specify, a
corresponding argument needs to be passed to the function when it is called, otherwise its
value becomes undefined. Let's consider the following example:

Example
Try this code »
// Defining function
function showFullname(firstName, lastName) {
alert(firstName + " " + lastName);
}

// Calling function
showFullname("Clark", "Kent"); // 0utputs: Clark Kent
showFullname("John"); // 0utputs: John undefined

Default Values for Function Parameters


With ES6, now you can specify default values to the function parameters. This means that if no
arguments are provided to function when it is called these default parameters values will be
used. This is one of the most awaited features in JavaScript. Here's an example:

Example
Try this code »
function sayHello(name = 'Guest') {
alert('Hello, ' + name);
}

sayHello(); // 0utputs: Hello, Guest


sayHello('John'); // 0utputs: Hello, John
While prior to ES6, to achieve the same we had to write something like this:
Example
Try this code »
function sayHello(name) {
var name = name || 'Guest';
alert('Hello, ' + name);
}

sayHello(); // 0utputs: Hello, Guest


sayHello('John'); // 0utputs: Hello, John
To learn about other ES6 features, please check out the JavaScript ES6 features chapter.

Returning Values from a Function


A function can return a value back to the script that called the function as a result using
the return statement. The value may be of any type, including arrays and objects.

The return statement usually placed as the last line of the function before the closing curly
bracket and ends it with a semicolon, as shown in the following example.

Example
Try this code »
// Defining function
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}

// Displaying returned value


alert(getSum(6, 20)); // 0utputs: 26
alert(getSum(-5, 17)); // 0utputs: 12
A function can not return multiple values. However, you can obtain similar results by returning
an array of values, as demonstrated in the following example.

Example
Try this code »
// Defining function
function divideNumbers(dividend, divisor){
var quotient = dividend / divisor;
var arr = [dividend, divisor, quotient];
return arr;
}

// Store returned value in a variable


var all = divideNumbers(10, 2);
// Displaying individual values
alert(all[0]); // 0utputs: 10
alert(all[1]); // 0utputs: 2
alert(all[2]); // 0utputs: 5

Working with Function Expressions


The syntax that we've used before to create functions is called function declaration. There is
another syntax for creating a function that is called a function expression.

Example
Try this code »
// Function Declaration
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}

// Function Expression
var getSum = function(num1, num2) {
var total = num1 + num2;
return total;
};
Once function expression has been stored in a variable, the variable can be used as a function:

Example
Try this code »
var getSum = function(num1, num2) {
var total = num1 + num2;
return total;
};

alert(getSum(5, 10)); // 0utputs: 15

var sum = getSum(7, 25);


alert(sum); // 0utputs: 32
Note: There is no need to put a semicolon after the closing curly bracket in a function
declaration. But function expressions, on the other hand, should always end with a semicolon.

Tip: In JavaScript functions can be stored in variables, passed into other functions as
arguments, passed out of functions as return values, and constructed at run-time.

The syntax of the function declaration and function expression looks very similar, but they
differ in the way they are evaluated, check out the following example:
Example
Try this code »
declaration(); // Outputs: Hi, I'm a function declaration!
function declaration() {
alert("Hi, I'm a function declaration!");
}

expression(); // Uncaught TypeError: undefined is not a function


var expression = function() {
alert("Hi, I'm a function expression!");
};
As you can see in the above example, the function expression threw an exception when it was
invoked before it is defined, but the function declaration executed successfully.

JavaScript parse declaration function before the program executes. Therefore, it doesn't
matter if the program invokes the function before it is defined because JavaScript has hoisted
the function to the top of the current scope behind the scenes. The function expression is not
evaluated until it is assigned to a variable; therefore, it is still undefined when invoked.

ES6 has introduced even shorter syntax for writing function expression which is called arrow
function, please check out the JavaScript ES6 features chapter to learn more about it.

Understanding the Variable Scope


However, you can declare the variables anywhere in JavaScript. But, the location of the
declaration determines the extent of a variable's availability within the JavaScript program i.e.
where the variable can be used or accessed. This accessibility is known as variable scope.

By default, variables declared within a function have local scope that means they cannot be
viewed or manipulated from outside of that function, as shown in the example below:

Example
Try this code »
// Defining function
function greetWorld() {
var greet = "Hello World!";
alert(greet);
}

greetWorld(); // Outputs: Hello World!

alert(greet); // Uncaught ReferenceError: greet is not defined


However, any variables declared in a program outside of a function has global scope i.e. it will
be available to all script, whether that script is inside a function or outside. Here's an example:
Example
Try this code »
var greet = "Hello World!";

// Defining function
function greetWorld() {
alert(greet);
}

greetWorld(); // Outputs: Hello World!

alert(greet); // Outputs: Hello World!

JavaScript Objects. What is an Object?


JavaScript is an object-based language and in JavaScript almost everything is an object or acts
like an object. So, to work with JavaScript effectively and efficiently we need to understand
how objects work as well as how to create your own objects and use them. A JavaScript object
is just a collection of named values. These named values are usually referred to as properties
of the object. If you remember from the JavaScript arrays chapter, an array is a collection of
values, where each value has an index (a numeric key) that starts from zero and increments by
one for each value. An object is similar to an array, but the difference is that you define the
keys yourself, such as name, age, gender, and so on. In the following sections we'll learn about
objects in detail.

Creating Objects
An object can be created with curly brackets {} with an optional list of properties. A property
is a "key: value" pair, where the key (or property name) is always a string, and value
(or property value) can be any data type, like strings, numbers, Booleans or complex data type
like arrays, functions, and other objects. Additionally, properties with functions as their values
are often called methods to distinguish them from other properties. A typical JavaScript object
may look like this:

Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};
The above example creates an object called person that has three properties name, age,
and gender and one method displayName(). The displayName() method displays the value
of this.name, which resolves to person.name. This is the easiest and preferred way to create a
new object in JavaScript, which is known as object literals syntax.

The property names generally do not need to be quoted unless they are reserved words, or if
they contain spaces or special characters (anything other than letters, numbers, and
the _ and $ characters), or if they start with a number, as shown in the following example:

Example
Try this code »
var person = {
"first name": "Peter",
"current age": 28,
gender: "Male"
};
Note: Since ECMAScript 5, reserved words can be used as object's property names without
quoting. However, you should avoid doing this for better compatibility.

Accessing Object's Properties


To access or get the value of a property, you can use the dot (.), or square bracket ([])
notation, as demonstrated in the following example:

Example
Try this code »
var book = {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000
};

// Dot notation
document.write(book.author); // Prints: J. K. Rowling

// Bracket notation
document.write(book["year"]); // Prints: 2000
The dot notation is easier to read and write, but it cannot always be used. If the name of the
property is not valid (i.e. if it contains spaces or special characters), you cannot use the dot
notation; you'll have to use bracket notation, as shown in the following example:

Example
Try this code »
var book = {
name: "Harry Potter and the Goblet of Fire",
author: "J. K. Rowling",
"publication date": "8 July 2000"
};

// Bracket notation
document.write(book["publication date"]); // Prints: 8 July 2000
The square bracket notation offers much more flexibility than dot notation. It also allows you
to specify property names as variables instead of just string literals, as shown in the example
below:

Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male"
};

var key = prompt("Enter any property name to get its value");


alert(person[key]); // Outputs: Peter (if enter "name")

Looping Through Object's Properties


You can iterate through the key-value pairs of an object using the for...in loop. This loop is
specially optimized for iterating over object's properties. Here's an example:

Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male"
};

// Iterating over object properties


for(var i in person) {
document.write(person[i] + "<br>"); // Prints: name, age and gender
}

Setting Object's Properties


Similarly, you can set the new properties or update the existing one using the dot ( .) or
bracket ([]) notation, as demonstrated in the following example:
Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male"
};

// Setting a new property


person.country = "United States";
document.write(person.country); // Prints: United States

person["email"] = "peterparker@mail.com";
document.write(person.email); // Prints: peterparker@mail.com

// Updating existing property


person.age = 30;
document.write(person.age); // Prints: 30

person["name"] = "Peter Parker";


document.write(person.name); // Prints: Peter Parker

Deleting Object's Properties


The delete operator can be used to completely remove properties from an object. Deleting is
the only way to actually remove a property from an object. Setting the property
to undefined or null only changes the value of the property. It does not remove property
from the object.

Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};

// Deleting property
delete person.age;
alert(person.age); // Outputs: undefined
Note: The delete operator only removes an object property or array element. It has no effect
on variables or declared functions. However, you should avoid delete operator for deleting an
array element, as it doesn't change the array's length, it just leaves a hole in the array.
Calling Object's Methods
You can access an object's method the same way as you would access properties—using the
dot notation or using the square bracket notation. Here's an example:

Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};

person.displayName(); // Outputs: Peter


person["displayName"](); // Outputs: Peter

Manipulating by Value vs. Reference


JavaScript objects are reference types that mean when you make copies of them, you're really
just copying the references to that object. Whereas primitive values like strings and numbers
are assigned or copied as a whole value. To better understand all this, let's check out the
following example:

Example
Try this code »
var message = "Hello World!";

var greet = message; // Assign message variable to a new variable


greet = "Hi, there!";

document.write(message); // Prints: Hello World!


document.write(greet); // Prints: Hi, there!
In the above example, we have made a copy of a variable message and changed the value of
that copy (i.e. variable greet). The two variables remain distinct and separate. But, if we do the
same thing with an object, we will get a different result, as you see in the following example:

Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male"
};

var user = person; // Assign person variable to a new variable


user.name = "Harry";

document.write(person.name); // Prints: Harry


document.write(user.name); // Prints: Harry
You can clearly see, any changes made to the variable user also change the person variable; it
happens because both variables reference the same object. So, simply copying the object
does not actually clone it but copies the reference to that object.

JavaScript DOM Nodes


Understanding the Document Object Model
The Document Object Model, or DOM for short, is a platform and language independent
model to represent the HTML or XML documents. It defines the logical structure of the
documents and the way in which they can be accessed and manipulated by an application
program. In the DOM, all parts of the document, such as elements, attributes, text, etc. are
organized in a hierarchical tree-like structure; similar to a family tree in real life that consists of
parents and children. In DOM terminology these individual parts of the document are known
as nodes. The Document Object Model that represents HTML document is referred to as
HTML DOM. Similarly, the DOM that represents the XML document is referred to as XML
DOM. In this chapter we'll cover the HTML DOM which provides a standard interface for
accessing and manipulating HTML documents through JavaScript. With the HTML DOM, you
can use JavaScript to build HTML documents, navigate their hierarchical structure, and add,
modify, or delete elements and attributes or their content, and so on. Almost anything found
in an HTML document can be accessed, changed, deleted, or added using the JavaScript with
the help of HTML DOM.

To understand this more clearly, let's consider the following simple HTML document:

Example
Try this code »
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Mobile OS</h1>
<ul>
<li>Android</li>
<li>iOS</li>
</ul>
</body>
</html>
The above HTML document can be represented by the following DOM tree:

The above diagram demonstrates the parent/child relationships between the nodes. The
topmost node i.e. the Document node is the root node of the DOM tree, which has one child,
the <html> element. Whereas, the <head> and <body> elements are the child nodes of
the <html> parent node. The <head> and <body> elements are also siblings since they are at the
same level. Further, the text content inside an element is a child node of the parent element.
So, for example, "Mobile OS" is considered as a child node of the <h1> that contains it, and so
on. Comments inside the HTML document are nodes in the DOM tree as well, even though it
doesn't affect the visual representation of the document in any way. Comments are useful for
documenting the code, however, you will rarely need to retrieve and manipulate them.

HTML attributes such as id, class, title, style, etc. are also considered as nodes in DOM
hierarchy but they don't participate in parent/child relationships like the other nodes do. They
are accessed as properties of the element node that contains them.
Each element in an HTML document such as image, hyperlink, form, button, heading,
paragraph, etc. is represented using a JavaScript object in the DOM hierarchy, and each object
contains properties and methods to describe and manipulate these objects. For example,
the style property of the DOM elements can be used to get or set the inline style of an element.

In the next few chapters we'll learn how to access individual elements on a web page and
manipulate them, for example, changing their style, content, etc. using the JavaScript
program.

Tip: The Document Object Model or DOM is, in fact, basically a representation of the various
components of the browser and the current Web document (HTML or XML) that can be
accessed or manipulated using a scripting language such as JavaScript.

JavaScript DOM Selectors


Selecting DOM Elements in JavaScript
JavaScript is most commonly used to get or modify the content or value of the HTML
elements on the page, as well as to apply some effects like show, hide, animations etc. But,
before you can perform any action you need to find or select the target HTML element.

In the following sections, you will see some of the common ways of selecting the elements on
a page and do something with them using the JavaScript.

Selecting the Topmost Elements


The topmost elements in an HTML document are available directly as document properties. For
example, the <html> element can be accessed with document.documentElement property,
whereas the <head> element can be accessed with document.head property, and
the <body> element can be accessed with document.body property. Here's an example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Topmost Elements</title>
</head>
<body>
<script>
// Display lang attribute value of html element
alert(document.documentElement.getAttribute("lang")); // Outputs: en
// Set background color of body element
document.body.style.background = "yellow";

// Display tag name of the head element's first child


alert(document.head.firstElementChild.nodeName); // Outputs: meta
</script>
</body>
</html>
But, be careful. If document.body is used before the <body> tag (e.g. inside the <head>), it will
return null instead of the body element. Because the point at which the script is executed,
the <body> tag was not parsed by the browser, so document.body is truly null at that point.

Let's take a look at the following example to better understand this:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Document.body Demo</title>
<script>
alert("From HEAD: " + document.body); // Outputs: null (since <body>
is not parsed yet)
</script>
</head>
<body>
<script>
alert("From BODY: " + document.body); // Outputs: HTMLBodyElement
</script>
</body>
</html>

Selecting Elements by ID
You can select an element based on its unique ID with the getElementById() method. This is
the easiest way to find an HTML element in the DOM tree.

The following example selects and highlight an element having the ID attribute id="mark".

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Element by ID</title>
</head>
<body>
<p id="mark">This is a paragraph of text.</p>
<p>This is another paragraph of text.</p>

<script>
// Selecting element with id mark
var match = document.getElementById("mark");

// Highlighting element's background


match.style.background = "yellow";
</script>
</body>
</html>
The getElementById() method will return the element as an object if the matching element
was found, or null if no matching element was found in the document.

Note: Any HTML element can have an id attribute. The value of this attribute must be unique
within a page i.e. no two elements in the same page can have the same ID.

Selecting Elements by Class Name


Similarly, you can use the getElementsByClassName() method to select all the elements
having specific class names. This method returns an array-like object of all child elements
which have all of the given class names. Let's check out the following example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements by Class Name</title>
</head>
<body>
<p class="test">This is a paragraph of text.</p>
<div class="block test">This is another paragraph of text.</div>
<p>This is one more paragraph of text.</p>

<script>
// Selecting elements with class test
var matches = document.getElementsByClassName("test");

// Displaying the selected elements count


document.write("Number of selected elements: " + matches.length);

// Applying bold style to first element in selection


matches[0].style.fontWeight = "bold";

// Applying italic style to last element in selection


matches[matches.length - 1].style.fontStyle = "italic";

// Highlighting each element's background through loop


for(var elem in matches) {
matches[elem].style.background = "yellow";
}
</script>
</body>
</html>

Selecting Elements by Tag Name


You can also select HTML elements by tag name using the getElementsByTagName() method.
This method also returns an array-like object of all child elements with the given tag name.

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements by Tag Name</title>
</head>
<body>
<p>This is a paragraph of text.</p>
<div class="test">This is another paragraph of text.</div>
<p>This is one more paragraph of text.</p>

<script>
// Selecting all paragraph elements
var matches = document.getElementsByTagName("p");

// Printing the number of selected paragraphs


document.write("Number of selected elements: " + matches.length);

// Highlighting each paragraph's background through loop


for(var elem in matches) {
matches[elem].style.background = "yellow";
}
</script>
</body>
</html>

Selecting Elements with CSS Selectors


You can use the querySelectorAll() method to select elements that matches the
specified CSS selector. CSS selectors provide a very powerful and efficient way of selecting
HTML elements in a document. Please check out the CSS tutorial section to learn more about
them. This method returns a list of all the elements that matches the specified selectors. You
can examine it just like any array, as shown in the following example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements with CSS Selectors</title>
</head>
<body>
<ul>
<li>Bread</li>
<li class="tick">Coffee</li>
<li>Pineapple Cake</li>
</ul>

<script>
// Selecting all li elements
var matches = document.querySelectorAll("ul li");

// Printing the number of selected li elements


document.write("Number of selected elements: " + matches.length +
"<hr>")

// Printing the content of selected li elements


for(var elem of matches) {
document.write(elem.innerHTML + "<br>");
}

// Applying line through style to first li element with class tick


matches = document.querySelectorAll("ul li.tick");
matches[0].style.textDecoration = "line-through";
</script>
</body>
</html>
Note: The querySelectorAll() method also supports CSS pseudo-classes like :first-
child, :last-child, :hover, etc. But, for CSS pseudo-elements such
as ::before, ::after, ::first-line, etc. this method always returns an empty list.

JavaScript DOM Styling


Styling DOM Elements in JavaScript
You can also apply style on HTML elements to change the visual presentation of HTML
documents dynamically using JavaScript. You can set almost all the styles for the elements
like, fonts, colors, margins, borders, background images, text alignment, width and height,
position, and so on. In the following section we'll discuss the various methods of setting styles
in JavaScript.

Setting Inline Styles on Elements


Inline styles are applied directly to the specific HTML element using the style attribute. In
JavaScript the style property is used to get or set the inline style of an element.

The following example will set the color and font properties of an element with id="intro".

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Set Inline Styles Demo</title>
</head>
<body>
<p id="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>

<script>
// Selecting element
var elem = document.getElementById("intro");

// Appling styles on element


elem.style.color = "blue";
elem.style.fontSize = "18px";
elem.style.fontWeight = "bold";
</script>
</body>
</html>

Naming Conventions of CSS Properties in JavaScript


Many CSS properties, such as font-size, background-image, text-decoration, etc. contain hyphens
(-) in their names. Since, in JavaScript hyphen is a reserved operator and it is interpreted as a
minus sign, so it is not possible to write an expression, like: elem.style.font-size

Therefore, in JavaScript, the CSS property names that contain one or more hyphens are
converted to intercapitalized style word. It is done by removing the hyphens and capitalizing
the letter immediately following each hyphen, thus the CSS property font-size becomes the
DOM property fontSize, border-left-style becomes borderLeftStyle, and so on.
Getting Style Information from Elements
Similarly, you get the styles applied on the HTML elements using the style property.

The following example will get the style information from the element having id="intro".

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Get Element's Style Demo</title>
</head>
<body>
<p id="intro" style="color:red; font-size:20px;">This is a
paragraph.</p>
<p>This is another paragraph.</p>

<script>
// Selecting element
var elem = document.getElementById("intro");

// Getting style information from element


alert(elem.style.color); // Outputs: red
alert(elem.style.fontSize); // Outputs: 20px
alert(elem.style.fontStyle); // Outputs nothing
</script>
</body>
</html>
The style property isn't very useful when it comes to getting style information from the
elements, because it only returns the style rules set in the element's style attribute not those
that come from elsewhere, such as style rules in the embedded style sheets, or external style
sheets.

To get the values of all CSS properties that are actually used to render an element you can use
the window.getComputedStyle() method, as shown in the following example:

Example
Try this code »
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Get Computed Style Demo</title>
<style type="text/css">
#intro {
font-weight: bold;
font-style: italic;
}
</style>
</head>
<body>
<p id="intro" style="color:red; font-size:20px;">This is a
paragraph.</p>
<p>This is another paragraph.</p>

<script>
// Selecting element
var elem = document.getElementById("intro");

// Getting computed style information


var styles = window.getComputedStyle(elem);

alert(styles.getPropertyValue("color")); // Outputs: rgb(255, 0, 0)


alert(styles.getPropertyValue("font-size")); // Outputs: 20px
alert(styles.getPropertyValue("font-weight")); // Outputs: 700
alert(styles.getPropertyValue("font-style")); // Outputs: italic
</script>
</body>
</html>
Tip: The value 700 for the CSS property font-weight is same as the keyword bold. The color
keyword red is same as rgb(255,0,0), which is the rgb notation of a color.

Adding CSS Classes to Elements


You can also get or set CSS classes to the HTML elements using the className property.

Since, class is a reserved word in JavaScript, so JavaScript uses the className property to refer
the value of the HTML class attribute. The following example will show to how to add a new
class, or replace all existing classes to a <div> element having id="info".

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Add or Replace CSS Classes Demo</title>
<style>
.highlight {
background: yellow;
}
</style>
</head>
<body>
<div id="info" class="disabled">Something very important!</div>

<script>
// Selecting element
var elem = document.getElementById("info");

elem.className = "note"; // Add or replace all classes with note


class
elem.className += " highlight"; // Add a new class highlight
</script>
</body>
</html>
There is even better way to work with CSS classes. You can use the classList property to get,
set or remove CSS classes easily from an element. This property is supported in all major
browsers except Internet Explorer prior to version 10. Here's an example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS classList Demo</title>
<style>
.highlight {
background: yellow;
}
</style>
</head>
<body>
<div id="info" class="disabled">Something very important!</div>

<script>
// Selecting element
var elem = document.getElementById("info");

elem.classList.add("hide"); // Add a new class


elem.classList.add("note", "highlight"); // Add multiple classes
elem.classList.remove("hide"); // Remove a class
elem.classList.remove("disabled", "note"); // Remove multiple classes
elem.classList.toggle("visible"); // If class exists remove it, if not
add it

// Determine if class exist


if(elem.classList.contains("highlight")) {
alert("The specified class exists on the element.");
}
</script>
</body>
</html>
JavaScript DOM Manipulation
Manipulating DOM Elements in JavaScript
Now that you've learnt how to select and style HTML DOM elements. In this chapter we will
learn how to add or remove DOM elements dynamically, get their contents, and so on.

Adding New Elements to DOM


You can explicitly create new element in an HTML document, using
the document.createElement() method. This method creates a new element, but it doesn't add it
to the DOM; you'll have to do that in a separate step, as shown in the following example:

Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
// Creating a new div element
var newDiv = document.createElement("div");

// Creating a text node


var newContent = document.createTextNode("Hi, how are you doing?");

// Adding the text node to the newly created div


newDiv.appendChild(newContent);

// Adding the newly created element and its content into the DOM
var currentDiv = document.getElementById("main");
document.body.appendChild(newDiv, currentDiv);
</script>
The appendChild() method adds the new element at the end of any other children of a specified
parent node. However, if you want to add the new element at the beginning of any other
children you can use the insertBefore() method, as shown in example below:

Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
// Creating a new div element
var newDiv = document.createElement("div");

// Creating a text node


var newContent = document.createTextNode("Hi, how are you doing?");

// Adding the text node to the newly created div


newDiv.appendChild(newContent);

// Adding the newly created element and its content into the DOM
var currentDiv = document.getElementById("main");
document.body.insertBefore(newDiv, currentDiv);
</script>

Getting or Setting HTML Contents to DOM


You can also get or set the contents of the HTML elements easily with the innerHTML property.
This property sets or gets the HTML markup contained within the element i.e. content
between its opening and closing tags. Checkout the following example to see how it works:

Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
// Getting inner HTML conents
var contents = document.getElementById("main").innerHTML;
alert(contents); // Outputs inner html contents

// Setting inner HTML contents


var mainDiv = document.getElementById("main");
mainDiv.innerHTML = "<p>This is <em>newly inserted</em> paragraph.</p>";
</script>
As you can see how easily you can insert new elements into DOM using
the innerHTML property, but there is one problem, the innerHTML property replaces all existing
content of an element. So if you want to insert the HTML into the document without replacing
the existing contents of an element, you can use the insertAdjacentHTML() method.

This method accepts two parameters: the position in which to insert and the HTML text to
insert. The position must be one of the following values: "beforebegin", "afterbegin", "beforeend",
and "afterend". This method is supported in all major browsers.

The following example shows the visualization of position names and how it works.
Example
Try this code »
<!-- beforebegin -->
<div id="main">
<!-- afterbegin -->
<h1 id="title">Hello World!</h1>
<!-- beforeend -->
</div>
<!-- afterend -->

<script>
// Selecting target element
var mainDiv = document.getElementById("main");

// Inserting HTML just before the element itself, as a previous sibling


mainDiv.insertAdjacentHTML('beforebegin', '<p>This is paragraph
one.</p>');

// Inserting HTML just inside the element, before its first child
mainDiv.insertAdjacentHTML('afterbegin', '<p>This is paragraph two.</p>');

// Inserting HTML just inside the element, after its last child
mainDiv.insertAdjacentHTML('beforeend', '<p>This is paragraph
three.</p>');

// Inserting HTML just after the element itself, as a next sibling


mainDiv.insertAdjacentHTML('afterend', '<p>This is paragraph four.</p>');
</script>
Note: The beforebegin and afterend positions work only if the node is in the DOM tree and has
a parent element. Also, when inserting HTML into a page, be careful not to use user input that
hasn't been escaped, to prevent XSS attacks.

Removing Existing Elements from DOM


Similarly, you can use the removeChild() method to remove a child node from the DOM. This
method also returns the removed node. Here's an example:

Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
var parentElem = document.getElementById("main");
var childElem = document.getElementById("hint");
parentElem.removeChild(childElem);
</script>
It is also possible to remove the child element without exactly knowing the parent element.
Simply find the child element and use the parentNode property to find its parent element. This
property returns the parent of the specified node in the DOM tree. Here's an example:

Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
var childElem = document.getElementById("hint");
childElem.parentNode.removeChild(childElem);
</script>

Replacing Existing Elements in DOM


You can also replace an element in HTML DOM with another using the replaceChild() method.
This method accepts two parameters: the node to insert and the node to be replaced. It has
the syntax like parentNode.replaceChild(newChild, oldChild);. Here's an example:

Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
var parentElem = document.getElementById("main");
var oldPara = document.getElementById("hint");

// Creating new elememt


var newPara = document.createElement("p");
var newContent = document.createTextNode("This is a new paragraph.");
newPara.appendChild(newContent);

// Replacing old paragraph with newly created paragraph


parentElem.replaceChild(newPara, oldPara);
</script>

JavaScript DOM Navigation


Navigating Between DOM Nodes
In the previous chapters you've learnt how to select individual elements on a web page. But
there are many occasions where you need to access a child, parent or ancestor element. See
the JavaScript DOM nodes chapter to understand the logical relationships between the nodes
in a DOM tree.

DOM node provides several properties and methods that allow you to navigate or traverse
through the tree structure of the DOM and make changes very easily. In the following section
we will learn how to navigate up, down, and sideways in the DOM tree using JavaScript.

Accessing the Child Nodes


You can use the firstChild and lastChild properties of the DOM node to access the first
and last direct child node of a node, respectively. If the node doesn't have any child element, it
returns null.

Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");
console.log(main.firstChild.nodeName); // Prints: #text

var hint = document.getElementById("hint");


console.log(hint.firstChild.nodeName); // Prints: SPAN
</script>
Note: The nodeName is a read-only property that returns the name of the current node as a
string. For example, it returns the tag name for element node, #text for text
node, #comment for comment node, #document for document node, and so on.

If you notice the above example, the nodeName of the first-child node of the main DIV element
returns #text instead of H1. Because, whitespace such as spaces, tabs, newlines, etc. are valid
characters and they form #text nodes and become a part of the DOM tree. Therefore, since
the <div> tag contains a newline before the <h1> tag, so it will create a #text node.

To avoid the issue with firstChild and lastChild returning #text or #comment nodes, you
could alternatively use the firstElementChild and lastElementChild properties to return
only the first and last element node, respectively. But, it will not work in IE 9 and earlier.
Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");
alert(main.firstElementChild.nodeName); // Outputs: H1
main.firstElementChild.style.color = "red";

var hint = document.getElementById("hint");


alert(hint.firstElementChild.nodeName); // Outputs: SPAN
hint.firstElementChild.style.color = "blue";
</script>
Similarly, you can use the childNodes property to access all child nodes of a given element,
where the first child node is assigned index 0. Here's an example:

Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");

// First check that the element has child nodes


if(main.hasChildNodes()) {
var nodes = main.childNodes;

// Loop through node list and display node name


for(var i = 0; i < nodes.length; i++) {
alert(nodes[i].nodeName);
}
}
</script>
The childNodes returns all child nodes, including non-element nodes like text and comment
nodes. To get a collection of only elements, use children property instead.

Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");

// First check that the element has child nodes


if(main.hasChildNodes()) {
var nodes = main.children;

// Loop through node list and display node name


for(var i = 0; i < nodes.length; i++) {
alert(nodes[i].nodeName);
}
}
</script>

Accessing the Parent Nodes


You can use the parentNode property to access the parent of the specified node in the DOM
tree.

The parentNode will always return null for document node, since it doesn't have a parent.

Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>

<script>
var hint = document.getElementById("hint");
alert(hint.parentNode.nodeName); // Outputs: DIV
alert(document.documentElement.parentNode.nodeName); // Outputs: #document
alert(document.parentNode); // Outputs: null
</script>
Tip: The topmost DOM tree nodes can be accessed directly as document properties. For
example, the <html> element can be accessed with document.documentElement property,
whereas the <head> element can be accessed with document.head property, and
the <body> element can be accessed with document.body property.

However, if you want to get only element nodes you can use the parentElement, like this:

Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>

<script>
var hint = document.getElementById("hint");
alert(hint.parentNode.nodeName); // Outputs: DIV
hint.parentNode.style.backgroundColor = "yellow";
</script>

Accessing the Sibling Nodes


You can use the previousSibling and nextSibling properties to access the previous and
next node in the DOM tree, respectively. Here's an example:

Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p><hr>
</div>

<script>
var title = document.getElementById("title");
alert(title.previousSibling.nodeName); // Outputs: #text

var hint = document.getElementById("hint");


alert(hint.nextSibling.nodeName); // Outputs: HR
</script>
Alternatively, you can use the previousElementSibling and nextElementSibling to get the
previous and next sibling element skipping any whitespace text nodes. All these properties
returns null if there is no such sibling. Here's an example:

Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>

<script>
var hint = document.getElementById("hint");
alert(hint.previousElementSibling.nodeName); // Outputs: H1
alert(hint.previousElementSibling.textContent); // Outputs: My Heading

var title = document.getElementById("title");


alert(title.nextElementSibling.nodeName); // Outputs: P
alert(title.nextElementSibling.textContent); // Outputs: This is some
text.
</script>
The textContent property represents the text content of a node and all of its descendants.
See the JavaScript DOM manipulation chapter to learn more about it.

Types of DOM Nodes


The DOM tree is consists of different types of nodes, such as elements, text, comments, etc.

Every node has a nodeType property that you can use to find out what type of node you are
dealing with. The following table lists the most important node types:

Constant Value Description

ELEMENT_NODE 1 An element node such as <p> or <img>.

TEXT_NODE 3 The actual text of element.

COMMENT_NODE 8 A comment node i.e. <!-- some comment -->

DOCUMENT_NODE 9 A document node i.e. the parent of <html> element.

DOCUMENT_TYPE_NODE 10 A document type node e.g. <!DOCTYPE html> for HTML5 documents.

JavaScript Window. The Window Object


The window object represents a window containing a DOM document. A window can be the
main window, a frame set or individual frame, or even a new window created with JavaScript.

If you remember from the preceding chapters we've used the alert() method in our scripts to
show popup messages. This is a method of the window object.

In the next few chapters we will see a number of new methods and properties of
the window object that enables us to do things such as prompt user for information, confirm
user's action, open new windows, etc. which lets you to add more interactivity to your web
pages.

Calculating Width and Height of the Window


The window object provides the innerWidth and innerHeight property to find out the width and
height of the browser window viewport (in pixels) including the horizontal and vertical
scrollbar, if rendered. Here's is an example that displays the current size of the window on
button click:

Example
Try this code »
<script>
function windowSize(){
var w = window.innerWidth;
var h = window.innerHeight;
alert("Width: " + w + ", " + "Height: " + h);
}
</script>

<button type="button" onclick="windowSize();">Get Window Size</button>


However, if you want to find out the width and height of the window excluding the scrollbars
you can use the clientWidth and clientHeight property of any DOM element (like a div), as
follow:

Example
Try this code »
<script>
function windowSize(){
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
alert("Width: " + w + ", " + "Height: " + h);
}
</script>

<button type="button" onclick="windowSize();">Get Window Size</button>


Note: The document.documentElement object represents the root element of the document, which
is the <html> element, whereas the document.body object represents the <body> element. Both are
supported in all major browsers.

JavaScript Window Screen. The Screen Object


The window.screen object contains information about the user's screen such as resolution (i.e.
width and height of the screen), color depth, pixel depth, etc. Since window object is at the
top of the scope chain, so properties of the window.screen object can be accessed without
specifying the window. prefix, for example window.screen.width can be written as screen.width. The
following section will show you how to get information of the user's display using the screen
object property of the window object.
Getting Width and Height of the Screen
You can use the screen.width and screen.height property obtains the width and height of the
user's screen in pixels. The following example will display your screen resolution on button
click:

Example
Try this code »
<script>
function getResolution() {
alert("Your screen is: " + screen.width + "x" + screen.height);
}
</script>

<button type="button" onclick="getResolution();">Get Resolution</button>

Getting Available Width and Height of the Screen


The screen.availWidth and screen.availHeight property can be used to get the width and height
available to the browser for its use on user's screen, in pixels.

The screen's available width and height is equal to screen's actual width and height minus
width and height of interface features like the taskbar in Windows. Here's an example:

Example
Try this code »
<script>
function getAvailSize() {
alert("Available Screen Width: " + screen.availWidth + ", Height: " +
screen.availHeight);
}
</script>

<button type="button" onclick="getAvailSize();">Get Available


Size</button>

Getting Screen Color Depth


You can use the screen.colorDepth property to get the color depth of the user's screen. Color
depth is the number of bits used to represent the color of a single pixel.
Color depth indicates how many colors a device screen is capable to produce. For example,
screen with color depth of 8 can produce 256 colors (28). Currently, most devices has screen
with color depth of 24 or 32. In simple words more bits produce more color variations, like 24
bits can produce 224 = 16,777,216 color variations (true colors), whereas 32 bits can produce
232 = 4,294,967,296 color variations (deep colors).

Example
Try this code »
<script>
function getColorDepth() {
alert("Your screen color depth is: " + screen.colorDepth);
}
</script>

<button type="button" onclick="getColorDepth();">Get Color Depth</button>


Tip: As of now virtually every computer and phone display uses 24-bit color depth. 24 bits
almost always uses 8 bits of each of R, G, B. Whereas in case of 32-bit color depth, 24 bits are
used for the color, and the remaining 8 bits are used for transparency.

Getting Screen Pixel Depth


You can get the pixel depth of the screen using the screen.pixelDepth property. Pixel depth is
the number of bits used per pixel by the system display hardware.

For modern devices, color depth and pixel depth are equal. Here's an example:

Example
Try this code »
<script>
function getPixelDepth() {
alert("Your screen pixel depth is: " + screen.pixelDepth);
}
</script>

<button type="button" onclick="getPixelDepth();">Get Pixel Depth</button>

JavaScript Window Location. The Location


Object
The location property of a window (i.e. window.location) is a reference to a Location object; it
represents the current URL of the document being displayed in that window.
Since window object is at the top of the scope chain, so properties of
the window.location object can be accessed without window. prefix, for
example window.location.href can be written as location.href. The following section will show
you how to get the URL of page as well as hostname, protocol, etc. using the location object
property of the window object.

Getting the Current Page URL


You can use the window.location.href property to get the entire URL of the current page.

The following example will display the complete URL of the page on button click:

Example
Try this code »
<script>
function getURL() {
alert("The URL of this page is: " + window.location.href);
}
</script>

<button type="button" onclick="getURL();">Get Page URL</button>

Getting Different Part of a URL


Similarly, you can use other properties of the location object such
as protocol, hostname, port, pathname, search, etc. to obtain different part of the URL.

Try out the following example to see how to use the location property of a window.

Example
Try this code »
// Prints complete URL
document.write(window.location.href);

// Prints protocol like http: or https:


document.write(window.location.protocol);

// Prints hostname with port like localhost or localhost:3000


document.write(window.location.host);

// Prints hostname like localhost or www.example.com


document.write(window.location.hostname);

// Prints port number like 3000


document.write(window.location.port);
// Prints pathname like /products/search.php
document.write(window.location.pathname);

// Prints query string like ?q=ipad


document.write(window.location.search);

// Prints fragment identifier like #featured


document.write(window.location.hash);
Note: When you visit a website, you're always connecting to a specific port (e.g.
http://localhost:3000). However, most browsers will simply not display the default port
numbers, for example, 80 for HTTP and 443 for HTTPS.

Loading New Documents


You can use the assign() method of the location object i.e. window.location.assign() to load
another resource from a URL provided as parameter, for example:

Example
Try this code »
<script>
function loadHomePage() {
window.location.assign("https://www.tutorialrepublic.com");
}
</script>

<button type="button" onclick="loadHomePage();">Load Home Page</button>


You can also use the replace() method to load new document which is almost the same
as assign(). The difference is that it doesn't create an entry in the browser's history, meaning
the user won't be able to use the back button to navigate to it. Here's an example:

Example
Try this code »
<script>
function loadHomePage(){
window.location.replace("https://www.tutorialrepublic.com");
}
</script>

<button type="button" onclick="loadHomePage();">Load Home Page</button>


Alternatively, you can use the window.location.href property to load new document in the
window. It produce the same effect as using assign() method. Here's is an example:

Example
Try this code »
<script>
function loadHomePage() {
window.location.href = "https://www.tutorialrepublic.com";
}
</script>

<button type="button" onclick="loadHomePage();">Load Home Page</button>

Reloading the Page Dynamically


The reload() method can be used to reload the current page dynamically.

You can optionally specify a Boolean parameter true or false. If the parameter is true, the
method will force the browser to reload the page from the server. If it is false or not specified,
the browser may reload the page from its cache. Here's an example:

Example
Try this code »
<script>
function forceReload() {
window.location.reload(true);
}
</script>

<button type="button" onclick="forceReload();">Reload Page</button>


Note: The result of calling reload() method is different from clicking browser's Reload/Refresh
button. The reload() method clears form control values that otherwise might be retained after
clicking the Reload/Refresh button in some browsers.

JavaScript Date and Time


Using the Date Object
The Date object is a built-in JavaScript object. It allows you to get the user's local time by
accessing the computer system clock through the browser. The Date object also provides
several methods for managing, manipulating, and formatting dates and times.

Creating a Date Object


Before we start working with the date and time, we need to create a Date object. Unlike other
built-in objects, such as arrays or functions, dates don't have a corresponding literal form: all
date objects need to be created using the Date constructor function which is Date().
There are four different ways to create a Date object in JavaScript.

The new Date() Syntax


You can simply declare a new Date object without initializing its value. In this case, the date
and time value will be set to the current date and time on the user's device on which the
script is run.

Example
Try this code »
var d = new Date();
document.write(d);

The new Date(year, month, ...) Syntax


You can also initialize a Date object by passing the following parameters separated by
commas: year, month, day, hours, minutes, seconds, and milliseconds.

The year and month parameters are required other parameters are optional.

Example
Try this code »
var d = new Date(2018,0,31,14,35,20,50);
document.write(d);
This date is actually represent 31 January 2018 at 14:35:20 and 50 milliseconds. You can
ignore the time part and specify just the date part if you wish.

The new Date(dateString) Syntax


JavaScript also allows you to create a Date object by passing the string representing a date, or
a date and time, as shown in the following example:

Example
Try this code »
var d = new Date("31 January 2018");
document.write(d);
This date represents 31 January 2018. You can also specify strings like Jan 31 2018, or any of a
number of valid variations, JavaScript will automatically handle that.
The new Date(milliseconds) Syntax
You can also define a Date object by passing the number of milliseconds since January 1,
1970, at 00:00:00 GMT. This time is known as the UNIX epoch because 1970 was the year when
the UNIX operating system was formally introduced. Here's an example:

Example
Try this code »
var d = new Date(1517356800000);
document.write(d);
The above date represents Wednesday 31 January 2018 05:30:00 GMT+0530.

Once you have created an instance of the Date object, you can use its methods to perform
various tasks, such as getting different component of a date, setting or modifying individual
date and time value, etc. These methods are described in detail in the following sections.

Note: JavaScript provides shortcuts called "literals" for creating most of the native object
without having to use the new operator, like new Object(), new Array(), etc.

Getting the Current Date and Time


To get the current date and time, create a new Date object without passing any parameters.
This will create an object with the current date and time. Here's an example:

Example
Try this code »
var now = new Date();
alert(now); // Display the current date and time
The output of this example will look something like this (depending on time zone offset):

Tue Aug 23 2022 16:28:53 GMT+0300 (East Africa Time)

Creating the Date and Time Strings


The JavaScript Date object provides several methods, such
as toDateString(), toLocaleDateString(), etc. to generate date strings in different formats.
Here's is an example:

Example
Try this code »
var d = new Date();
alert(d.toDateString()); // Display an abbreviated date string
alert(d.toLocaleDateString()); // Display a localized date string
alert(d.toISOString()); // Display the ISO standardized date string
alert(d.toUTCString()); // Display a date string converted to UTC time
alert(d.toString()); // Display the full date string with local time zone
Similarly, you can use the toLocaleTimeString(), toTimeString() methods of the Date
object to generate time strings, as shown in the following example:

Example
Try this code »
var d = new Date();
alert(d.toTimeString()); // Display the time portion of the date
alert(d.toLocaleTimeString()); // Display a localized time string

Getting Specific Date and Time Components


Once you have a proper date object, a number of methods are available to you to extract
details from it, such as the month, date, hours or minutes value etc. The following section
describes the various methods of extracting individual pieces of information from a Date
object.

Getting the Year, Month and Date


The Date object provides several methods such as getFullYear(), getMonth(), getDay(), etc.
that you can use to extract the specific date components from the Date object, such as year,
day of month, day of week, etc. respectively. The following example demonstrates how to get
specific date components from the Date object using these methods:

Example
Try this code »
var d = new Date();
// Extracting date part
alert(d.getDate()); // Display the day of the month
alert(d.getDay()); // Display the number of days into the week (0-6)
alert(d.getMonth()); // Display the number of months into the year (0-11)
alert(d.getFullYear()); // Display the full year (four digits)
The getDay() method returns a number representing the day of the week (from 0 to 6)
instead of returning a name such as Sunday or Monday in such a way that, if it is Sunday, the
method returns 0; and if it is Monday , the method returns 1, and so on.

Likewise, the getMonth() method returns the number of months (from 0 to 11) instead of
name of the month. Here 0 represents the first month of the year. Therefore, if it is January
the method returns 0 not 1; and if it is August, the method returns 7.
Getting the Hours, Minutes, Seconds, and Milliseconds
Similarly, the Date object provides methods
like getHours(), getMinutes(), getSeconds(), getTimezoneOffset() etc. to extract the time
components from the Date object.

Example
Try this code »
var d = new Date();
// Extracting time part
alert(d.getHours()); // Display the number of hours into the day (0-23)
alert(d.getMinutes()); // Display the number of minutes into the hour (0-
59)
alert(d.getSeconds()); // Display the seconds into the minute (0-59)
alert(d.getMilliseconds()); // Display the number of milliseconds into
second (0-999)
alert(d.getTime()); // Display the number of milliseconds since 1/1/1970
alert(d.getTimezoneOffset()); // Display the time-zone offset (from
Greenwich Mean Time) in minutes
The getHours() method returns the number of hours into the day (from 0 to 23) according to
the 24-hour clock. So, when it is midnight, the method returns 0; and when it is 3:00 P.M., it
returns 15.

Note: The Date objects also have methods to obtain the UTC components. Just place UTC
after get, such as getUTCDate(), getUTCHour(), getUTCMinutes(), and so on.

Setting the Date and Time Values


In addition to retrieving date and time values, you can also set or modify these values using
the JavaScript. This is most often used in program where you have to change the value of a
date object from one particular date or time to another. Let's see how it works.

Setting the Year, Month and Date


The Date object provides methods such
as setFullYear(), setMonth() and setDate() methods to set the year, month, date
components of the Date object respectively.

For instance, in the following example we have used setFullYear() method to change the
current date stored in a variable ahead of two year in the future.

Example
Try this code »
var d = new Date();
d.setFullYear(d.getFullYear() + 2);
alert(d); // Display future date
The output of the above example will look something like this:

Fri Aug 23 2024 16:28:53 GMT+0300 (East Africa Time)

Likewise, you can use the setMonth() method to set or modify the month part of a Date
object.

Example
Try this code »
var d = new Date(); // Current date and time
d.setMonth(0); // Sets month to 0, January
document.write(d);
The setMonth() method require an integer value from 0 to 11, if you set the value of the
month greater than 11, the year value of the date object will increment.

In other words, a value of 12 results in the year value increasing by 1, and the month value set
to 0, as demonstrated in the following example:

Example
Try this code »
var d = new Date(2018, 5, 24); // June 24, 2018
d.setMonth(12); // Sets month to 12, new date will be January 24, 2019
document.write(d);
Similarly, you can modify the date part of the date object, like this:

Example
Try this code »
var d = new Date(2018, 5, 24); // June 24, 2018
d.setDate(15); // Sets date to 15, new date will be June 15, 2018
document.write(d);
The setDate() method require an integer value from 1 to 31. Also, if you pass the values
greater than the number of days in the month, the month will increment. For example:

Example
Try this code »
var d = new Date(2018, 5, 24); // June 24, 2018
d.setDate(36); // Sets day to 36, new date will be July 6, 2018
document.write(d);
Setting the Hours, Minutes and Seconds
Methods for setting the time values are also pretty straight forward.
The setHours(), setMinutes(), setSeconds(), setMilliseconds() can be used to set the
hour, minutes, seconds, and milliseconds part of the Date object respectively.

Each method takes integer values as parameters. Hours range from 0 to 23. Minutes and
seconds range from 0 to 59. And milliseconds range from 0 to 999. Here is an example:

Example
Try this code »
var d = new Date(2018, 5, 24); // June 24, 2018 00:00:00
d.setHours(8);
d.setMinutes(30);
d.setSeconds(45);
d.setMilliseconds(600);
document.write(d);
The output of the above example will look something like the following:

Sun Jun 24 2018 08:30:45 GMT+0300 (East Africa Time)

avaScript Date and Time


In this tutorial you will learn how to work with date and time in JavaScript.

Using the Date Object


The Date object is a built-in JavaScript object. It allows you to get the user's local time by
accessing the computer system clock through the browser. The Date object also provides
several methods for managing, manipulating, and formatting dates and times.

Creating a Date Object


Before we start working with the date and time, we need to create a Date object. Unlike other
built-in objects, such as arrays or functions, dates don't have a corresponding literal form: all
date objects need to be created using the Date constructor function which is Date().

There are four different ways to create a Date object in JavaScript.


The new Date() Syntax
You can simply declare a new Date object without initializing its value. In this case, the date
and time value will be set to the current date and time on the user's device on which the
script is run.

Example
Try this code »
var d = new Date();
document.write(d);

The new Date(year, month, ...) Syntax


You can also initialize a Date object by passing the following parameters separated by
commas: year, month, day, hours, minutes, seconds, and milliseconds.

The year and month parameters are required other parameters are optional.

Example
Try this code »
var d = new Date(2018,0,31,14,35,20,50);
document.write(d);
This date is actually represent 31 January 2018 at 14:35:20 and 50 milliseconds. You can
ignore the time part and specify just the date part if you wish.

The new Date(dateString) Syntax


JavaScript also allows you to create a Date object by passing the string representing a date, or
a date and time, as shown in the following example:

Example
Try this code »
var d = new Date("31 January 2018");
document.write(d);
This date represents 31 January 2018. You can also specify strings like Jan 31 2018, or any of a
number of valid variations, JavaScript will automatically handle that.
The new Date(milliseconds) Syntax
You can also define a Date object by passing the number of milliseconds since January 1,
1970, at 00:00:00 GMT. This time is known as the UNIX epoch because 1970 was the year when
the UNIX operating system was formally introduced. Here's an example:

Example
Try this code »
var d = new Date(1517356800000);
document.write(d);
The above date represents Wednesday 31 January 2018 05:30:00 GMT+0530.

Once you have created an instance of the Date object, you can use its methods to perform
various tasks, such as getting different component of a date, setting or modifying individual
date and time value, etc. These methods are described in detail in the following sections.

Note: JavaScript provides shortcuts called "literals" for creating most of the native object
without having to use the new operator, like new Object(), new Array(), etc.

Getting the Current Date and Time


To get the current date and time, create a new Date object without passing any parameters.
This will create an object with the current date and time. Here's an example:

Example
Try this code »
var now = new Date();
alert(now); // Display the current date and time
The output of this example will look something like this (depending on time zone offset):

Tue Aug 23 2022 16:28:53 GMT+0300 (East Africa Time)

Creating the Date and Time Strings


The JavaScript Date object provides several methods, such
as toDateString(), toLocaleDateString(), etc. to generate date strings in different formats.
Here's is an example:

Example
Try this code »
var d = new Date();
alert(d.toDateString()); // Display an abbreviated date string
alert(d.toLocaleDateString()); // Display a localized date string
alert(d.toISOString()); // Display the ISO standardized date string
alert(d.toUTCString()); // Display a date string converted to UTC time
alert(d.toString()); // Display the full date string with local time zone
Similarly, you can use the toLocaleTimeString(), toTimeString() methods of the Date
object to generate time strings, as shown in the following example:

Example
Try this code »
var d = new Date();
alert(d.toTimeString()); // Display the time portion of the date
alert(d.toLocaleTimeString()); // Display a localized time string

Getting Specific Date and Time Components


Once you have a proper date object, a number of methods are available to you to extract
details from it, such as the month, date, hours or minutes value etc. The following section
describes the various methods of extracting individual pieces of information from a Date
object.

Getting the Year, Month and Date


The Date object provides several methods such as getFullYear(), getMonth(), getDay(), etc.
that you can use to extract the specific date components from the Date object, such as year,
day of month, day of week, etc. respectively. The following example demonstrates how to get
specific date components from the Date object using these methods:

Example
Try this code »
var d = new Date();
// Extracting date part
alert(d.getDate()); // Display the day of the month
alert(d.getDay()); // Display the number of days into the week (0-6)
alert(d.getMonth()); // Display the number of months into the year (0-11)
alert(d.getFullYear()); // Display the full year (four digits)
The getDay() method returns a number representing the day of the week (from 0 to 6)
instead of returning a name such as Sunday or Monday in such a way that, if it is Sunday, the
method returns 0; and if it is Monday , the method returns 1, and so on.

Likewise, the getMonth() method returns the number of months (from 0 to 11) instead of
name of the month. Here 0 represents the first month of the year. Therefore, if it is January
the method returns 0 not 1; and if it is August, the method returns 7.
Getting the Hours, Minutes, Seconds, and Milliseconds
Similarly, the Date object provides methods
like getHours(), getMinutes(), getSeconds(), getTimezoneOffset() etc. to extract the time
components from the Date object.

Example
Try this code »
var d = new Date();
// Extracting time part
alert(d.getHours()); // Display the number of hours into the day (0-23)
alert(d.getMinutes()); // Display the number of minutes into the hour (0-
59)
alert(d.getSeconds()); // Display the seconds into the minute (0-59)
alert(d.getMilliseconds()); // Display the number of milliseconds into
second (0-999)
alert(d.getTime()); // Display the number of milliseconds since 1/1/1970
alert(d.getTimezoneOffset()); // Display the time-zone offset (from
Greenwich Mean Time) in minutes
The getHours() method returns the number of hours into the day (from 0 to 23) according to
the 24-hour clock. So, when it is midnight, the method returns 0; and when it is 3:00 P.M., it
returns 15.

Note: The Date objects also have methods to obtain the UTC components. Just place UTC
after get, such as getUTCDate(), getUTCHour(), getUTCMinutes(), and so on.

Setting the Date and Time Values


In addition to retrieving date and time values, you can also set or modify these values using
the JavaScript. This is most often used in program where you have to change the value of a
date object from one particular date or time to another. Let's see how it works.

Setting the Year, Month and Date


The Date object provides methods such
as setFullYear(), setMonth() and setDate() methods to set the year, month, date
components of the Date object respectively.

For instance, in the following example we have used setFullYear() method to change the
current date stored in a variable ahead of two year in the future.

Example
Try this code »
var d = new Date();
d.setFullYear(d.getFullYear() + 2);
alert(d); // Display future date
The output of the above example will look something like this:

Fri Aug 23 2024 16:28:53 GMT+0300 (East Africa Time)

Likewise, you can use the setMonth() method to set or modify the month part of a Date
object.

Example
Try this code »
var d = new Date(); // Current date and time
d.setMonth(0); // Sets month to 0, January
document.write(d);
The setMonth() method require an integer value from 0 to 11, if you set the value of the
month greater than 11, the year value of the date object will increment.

In other words, a value of 12 results in the year value increasing by 1, and the month value set
to 0, as demonstrated in the following example:

Example
Try this code »
var d = new Date(2018, 5, 24); // June 24, 2018
d.setMonth(12); // Sets month to 12, new date will be January 24, 2019
document.write(d);
Similarly, you can modify the date part of the date object, like this:

Example
Try this code »
var d = new Date(2018, 5, 24); // June 24, 2018
d.setDate(15); // Sets date to 15, new date will be June 15, 2018
document.write(d);
The setDate() method require an integer value from 1 to 31. Also, if you pass the values
greater than the number of days in the month, the month will increment. For example:

Example
Try this code »
var d = new Date(2018, 5, 24); // June 24, 2018
d.setDate(36); // Sets day to 36, new date will be July 6, 2018
document.write(d);
Setting the Hours, Minutes and Seconds
Methods for setting the time values are also pretty straight forward.
The setHours(), setMinutes(), setSeconds(), setMilliseconds() can be used to set the
hour, minutes, seconds, and milliseconds part of the Date object respectively.

Each method takes integer values as parameters. Hours range from 0 to 23. Minutes and
seconds range from 0 to 59. And milliseconds range from 0 to 999. Here is an example:

Example
Try this code »
var d = new Date(2018, 5, 24); // June 24, 2018 00:00:00
d.setHours(8);
d.setMinutes(30);
d.setSeconds(45);
d.setMilliseconds(600);
document.write(d);
The output of the above example will look something like the following:

Sun Jun 24 2018 08:30:45 GMT+0300 (East Africa Time)

Using the Math Object


The JavaScript Math object provides a number of useful properties and methods for
performing mathematical tasks like, generating random numbers, rounding numbers,
obtaining values such as PI and performing calculation, and so on. It also includes methods
for performing mathematical task that are normally impossible or too complex to perform
using standard mathematical operators (+, -,*, and /) such as calculating sine or cosine values.

The Math.PI Property


The Math.PI property represents the ratio of the circumference of a circle to its diameter. PI
(π) is a mathematical constant, which is approximately 3.14159: Math.PI = π ≈ 3.14159

Here is an example that calculates the area of a circle using the Math.PI property.

Example
Try this code »
// Printing PI value
document.write(Math.PI); // Prints: 3.141592653589793

// Function to calculate circle area


function calculateCircleArea(radius){
var area = (Math.PI) * radius * radius;
return area;
}

document.write(calculateCircleArea(5)); // Prints: 78.53981633974483


document.write(calculateCircleArea(10)); // Prints: 314.1592653589793
Note: The Math object is a built-in JavaScript object so its properties and methods can be
accessed directly. You'll never need to create a Math object, because it is automatically
created by the JavaScript interpreter.

Getting the Absolute Value


The Math.abs() method is used to calculate the absolute (positive) value of a number.
Therefore, -1 is returned as 1, -5 as 5, and so on. Here is an example:

Example
Try this code »
document.write(Math.abs(-1)); // Prints: 1
document.write(Math.abs(1)); // Prints: 1
document.write(Math.abs(-5)); // Prints: 5
document.write(Math.abs(-10.5)); // Prints: 10.5

Generating a Random Number


The Math.random() method is used to generate a floating-point random number in the range
from 0 inclusive up to but not including 1. However, if you want a random integer between
zero and an integer higher than one, you could use the following solution:

Example
Try this code »
document.write(Math.random()); // Expected output: a number between 0 and
1

// Function to create random integer


function getRandomInt(max) {
return Math.floor(Math.random() * max);
}

document.write(getRandomInt(3)); // Expected output: 0, 1 or 2


document.write(getRandomInt(1)); // Expected output: 0

Calculating the Square Root of a Number


The Math.sqrt() method is used to calculate the square root of a number: Math.sqrt(x) = x

If the number is negative, NaN is returned. Here is an example:


Example
Try this code »
document.write(Math.sqrt(4)); // Prints: 2
document.write(Math.sqrt(16)); // Prints: 4
document.write(Math.sqrt(0.25)); // Prints: 0.5
document.write(Math.sqrt(-9)); // Prints: NaN

/* Function to calculate hypotenuse.


Hypotenuse is the longest side of a right-angled triangle. */
function calculateHypotenuse(a, b) {
return Math.sqrt((a * a) + (b * b));
}

document.write(calculateHypotenuse(3, 4)); // Prints: 5


document.write(calculateHypotenuse(5, 12)); // Prints: 13

Rounding Numbers
The JavaScript Math object provides few methods to round numbers, each one has its own
purpose. The following section will describe these methods in detials.

The ceil() Method


The Math.ceil() method rounds a number up to the next highest integer. So, 3.5 becomes 4,
-5.7 becomes -5 (because -5 is greater than -6). Here's an example:

Example
Try this code »
document.write(Math.ceil(3.5)); // Prints: 4
document.write(Math.ceil(-5.7)); // Prints: -5
document.write(Math.ceil(9.99)); // Prints: 10
document.write(Math.ceil(-9.99)); // Prints: -9
document.write(Math.ceil(0)); // Prints: 0

The floor() Method


The Math.floor() method rounds a number down to the next lowest integer. So, 3.5 becomes
3, -5.7 becomes -6 (because -6 is lesser than -5). Here's an example:

Example
Try this code »
document.write(Math.floor(3.5)); // Prints: 3
document.write(Math.floor(-5.7)); // Prints: -6
document.write(Math.floor(9.99)); // Prints: 9
document.write(Math.floor(-9.99)); // Prints: -10
document.write(Math.floor(0)); // Prints: 0

The round() Method


The Math.round() method rounds a number to the nearest integer in such a way that if the
decimal part is .5 or greater, number is rounded up, otherwise rounded down. So, 3.5
becomes 4, -5.7 becomes -6, 4.49 becomes 4, and so on. Here's an example:

Example
Try this code »
document.write(Math.round(3.5)); // Prints: 4
document.write(Math.round(-5.7)); // Prints: -6
document.write(Math.round(7.25)); // Prints: 7
document.write(Math.round(4.49)); // Prints: 4
document.write(Math.round(0)); // Prints: 0

Finding the Largest and Smallest Numbers


The Math.max() and Math.min() methods is used to find which number is the largest or
smallest in a group of numbers, respectively. Here's an example:

Example
Try this code »
document.write(Math.max(1, 3, 2)); // Prints: 3
document.write(Math.max(-1, -3, -2)); // Prints: -1

document.write(Math.min(1, 3, 2)); // Prints: 1


document.write(Math.min(-1, -3, -2)); // Prints: -3
You can also find the maximum or minimum value within an array or an array-like object using
the apply() method, as shown in the following example:

Example
Try this code »
var numbers = [1, 3, 2];

document.write(Math.max.apply(null, numbers)); // Prints: 3


document.write(Math.min.apply(null, numbers)); // Prints: 1
There is even simpler way to do this. In ECMAScript 6 you can accomplish the same thing
using the new spread operator (...), as shown in example below:

Example
Try this code »
var numbers = [1, 3, 2];

document.write(Math.max(...numbers)); // Prints: 3
document.write(Math.min(...numbers)); // Prints: 1

Raising Numbers to a Power


The Math.pow() method is used to raise a number to a specified power.

The expression Math.pow(x, y)—equivalent to mathmatically xy—shows how many times


the base x is multiplied by the exponent y. Here's an example:

Example
Try this code »
document.write(Math.pow(3, 2)); // Prints: 9
document.write(Math.pow(0, 1)); // Prints: 0
document.write(Math.pow(5, -2)); // Prints: 0.04
document.write(Math.pow(16, 0.5)); // Prints: 4 (square root of 4)
document.write(Math.pow(8, 1/3)); // Prints: 2 (cube root of 8)
A positive exponent indicates multiplication (52 = 5 x 5 = 25), a negative exponent indicates
division (5-2 = 1/52 = 0.04), whereas a fractional exponent indicates a root of the base.

Performing Trigonometric Operations


The JavaScript's Math object also provides several trigonometric methods such
as sin(), cos(), tan() to perform trigonometric operations. These methods work in radians,
so you need to multiply any degree measurements by π/180 before using them.

Since, pi radians are equal to 180 degrees: π rad = 180°. Therefore, π/2 radians is equal 90
degrees, π/3 radians is equal to 60 degrees, and so on. Here's an example:

Example
Try this code »
document.write(Math.sin(0 * Math.PI / 180)); // Prints: 0
document.write(Math.sin(90 * Math.PI / 180)); // Prints: 1
document.write(Math.cos(0 * Math.PI / 180)); // Prints: 1
document.write(Math.cos(180 * Math.PI / 180)); // Prints: -1
document.write(Math.tan(0 * Math.PI / 180)); // Prints: 0

JavaScript Type Conversions


Automatic Type Conversions
Most of the time JavaScript automatically converts values from one data type to another when
used in expression. For example, in mathematical operations values are automatically
converted to numbers. However, the end result is not always what you expected:

Example
Try this code »
alert("3" - 2); // Outputs: 1
alert("3" + 2); // Outputs: "32" (because + is also concatenation
operator)
alert(3 + "2"); // Outputs: "32"
alert("3" * "2"); // Outputs: 6
alert("10" / "2"); // Outputs: 5
alert(1 + true); // Outputs: 2 (because true is converted to 1)
alert(1 + false); // Outputs: 1 (because false is converted to 0)
alert(1 + undefined); // Outputs: NaN
alert(3 + null); // Outputs: 3 (because null is converted to 0)
alert("3" + null); // Outputs: "3null"
alert(true + null); // Outputs: 1
alert(true + undefined); // Outputs: NaN
There are situations when we need to manually convert a value from one data type to
another. JavaScript provides a number of different methods to perform such data type
conversion task. In the following sections we will discuss those methods in detail.

Converting Values to Numbers


The numeric conversion is usually required when we read the value from a string-based
source like a text input, but we expect a number to be entered, or want to treat it as a
number.

In such situations, you can use the global method Number() to convert strings to numbers.

Example
Try this code »
var str = "123";
alert(typeof str); // Outputs: string

var num = Number(str); // Becomes a number 123


alert(typeof num); // Outputs: number
If the string is not a valid number, the result will be NaN. Empty strings convert to 0.

Example
Try this code »
Number("10.5") // returns 10.5
Number(true) // returns 1
Number(false) // returns 0
Number(null) // returns 0
Number(" 123 ") // returns 123
Number(" ") // returns 0
Number("") // returns 0
Number("123e-1") // returns 12.3
Number("0xFF") // returns 255 (hexadecimal representation)
Number("undefined") // returns NaN
Number("null") // returns NaN
Number("Hello World!") // returns NaN

Converting Values to Strings


Similarly, you can use the String() method to convert a value to a string.

The following example will show you how to convert a Boolean value to a string.

Example
Try this code »
var bool = true;
alert(typeof bool); // Outputs: boolean

var str = String(bool); // Becomes a string "true"


alert(typeof str); // Outputs: string
The String() method can be used on any type of numbers, variables, or expressions:

Example
Try this code »
String(10.5) // returns "10.5"
String(123) // returns "123"
String(100 + 23) // returns "123"
String(true) // returns "true"
String(false) // returns "false"
String(123e-1) // returns "12.3"
String(0xFF) // returns "255"
String(undefined) // returns "undefined"
String(null) // returns "null"
Another technique for converting numbers to strings is using the toString() method:

Example
Try this code »
var num = 123;
alert(typeof num); // Outputs: number
var str = num.toString(); // Becomes a string "123"
alert(typeof str); // Outputs: string

Converting Values to Boolean


Boolean conversions are also pretty straight forward. You can use the Boolean() method to
convert any value to a Boolean value (i.e. true or false).

Values that are intuitively empty, like 0, null, false, undefined, NaN or an empty string ("")
become false. Other values become true, as shown in the example here:

Example
Try this code »
Boolean(0) // returns false
Boolean(null) // returns false
Boolean(false) // returns false
Boolean(undefined) // returns false
Boolean(NaN) // returns false
Boolean("") // returns false
Boolean("0") // returns true
Boolean(1) // returns true
Boolean(true) // returns true
Boolean("false") // returns true
Boolean("Hello World!") // returns true
Boolean(" ") // returns true
If you see the example carefully you'll find the Boolean() method returns true for the string with
zero "0", and string "false", whereas it returns false for the values 0 and false.

Note: In some programming languages (namely PHP) the string "0" is treated as false. But in
JavaScript a non-empty string is always true.

Object to Primitive Conversions


All the conversions we've seen so far are performed on primitive types (data types that can
hold only a single value at a time). But what happens with complex data types such as object,
let's see.

JavaScript automatically perform object-to-string conversion when we try to print out an


object like alert(obj) or document.write(obj). Likewise, the object-to-number conversions are
automatically performed when we try to add or subtract objects or apply mathematical
functions, for example, adding or subtracting date objects. Here's an example:

Example
Try this code »
var date1 = new Date(2018, 5, 24);
alert(date1); // Display date string like: Sun Jun 24 2018 00:00:00

var date2 = new Date(2025, 8, 15);


var time = date2 - date1;
alert(time) // Display time in milliseconds: 228096000000
You can also perform the object-to-string conversion manually using the toString() method,
which return a string representation of the object. Additionally, you can use
the valueOf() method on some objects such as Date to perform object-to-number conversion.
Here's an example:

Example
Try this code »
var arr = [1, 2, 3];
arr.toString(); // returns "1,2,3"

var d = new Date(2018, 5, 24);


d.toDateString(); // returns date like Sun Jun 24 2018 00:00:00
d.valueOf(); // returns 1529778600000
Note: Object-to-Boolean conversion are insignificant, because all objects (including arrays
and functions) are true in a boolean context. So there are only string and numeric conversions.

Type Conversions Using Operators


Certain JavaScript operators, such as + and - operators, can also be used to perform type
conversions, as demonstrated in the following example:

Example
Try this code »
var x = "10"; // x is a string
var y = +x;
alert(typeof(y)); // Outputs: number
alert(y); // Outputs: 10

var x = 10; // x is a number


var y = x + "";
alert(typeof(y)); // Outputs: string
alert(y); // Outputs: 10

var x = "15"; // x is a string


var y = x - 0;
alert(typeof(y)); // Outputs: number
alert(y); // Outputs: 15

var x = "123";
alert(typeof(!!x)); // Outputs: boolean
alert(!!x); // Outputs: true
var x = "Hello World!";
var y = +x;
alert(typeof(y));// Outputs: number
alert(y); // Outputs: NaN

JavaScript Event Listeners


Understanding Event Listeners
The event listeners are just like event handlers, except that you can assign as many event
listeners as you like to a particular event on particular element.

To understand how event listeners actually works let's check out a simple example. Suppose
that you've created two functions and you try to execute both of them on click of the button
using the onclick event handler, as shown in the following example:

Example
Try this code »
<button id="myBtn">Click Me</button>

<script>
// Defining custom functions
function firstFunction() {
alert("The first function executed successfully!");
}

function secondFunction() {
alert("The second function executed successfully");
}

// Selecting button element


var btn = document.getElementById("myBtn");

// Assigning event handlers to the button


btn.onclick = firstFunction;
btn.onclick = secondFunction; // This one overwrite the first
</script>
If you run the above example and click the button element, only secondFunction() will be
executed, because assigning the second event handler overwrites the first.

This is the main shortcoming of this classic event model—you can only assign one event
handler to a particular event on a particular element i.e. a single function per event per
element. To deal with this problem W3C introduced more flexible event-model called event
listeners.
Any HTML element can have multiple event listeners, therefore you can assign multiple
functions to the same event for the same element, as demonstrated in following example:

Example
Try this code »
<button id="myBtn">Click Me</button>

<script>
// Defining custom functions
function firstFunction() {
alert("The first function executed successfully!");
}

function secondFunction() {
alert("The second function executed successfully");
}

// Selecting button element


var btn = document.getElementById("myBtn");

// Assigning event listeners to the button


btn.addEventListener("click", firstFunction);
btn.addEventListener("click", secondFunction);
</script>
Now, if you run the above example and click the button, both functions will be executed.

In addition to the event type and listener function parameter the addEventListener() accepts
one more Boolean parameter useCapture. This is an optional parameter which specifies
whether to use event bubbling or event capturing. Its basic syntax is:
target.addEventListener(event, function, useCapture);

Event bubbling and capturing are two ways of propagating events. We will learn about event
propagation in detail in the upcoming chapter.

Adding Event Listeners for Different Event Types


Like event handler, you can assign different event listeners to different event types on the
same element. The following example will assign different event-listener functions to the
"click", "mouseover", and "mouseout" events of a button element.

Example
Try this code »
<button id="myBtn">Click Me</button>

<script>
// Selecting button element
var btn = document.getElementById("myBtn");

// Defining custom functions


function sayHello() {
alert("Hi, how are you doing?");
}

function setHoverColor() {
btn.style.background = "yellow";
}

function setNormalColor() {
btn.style.background = "";
}

// Assigning event listeners to the button


btn.addEventListener("click", sayHello);
btn.addEventListener("mouseover", setHoverColor);
btn.addEventListener("mouseout", setNormalColor);
</script>

Adding Event Listeners to Window Object


The addEventListener() method allows you to add event listeners to any HTML DOM
elements, the document object, the window object, or any other object that support events,
e.g, XMLHttpRequest object. Here's an example that attaches an event listener to the window
"resize" event:

Example
Try this code »
<div id="result"></div>

<script>
// Defining event listener function
function displayWindowSize() {
var w = window.innerWidth;
var h = window.innerHeight;
var size = "Width: " + w + ", " + "Height: " + h;
document.getElementById("result").innerHTML = size;
}

// Attaching the event listener function to window's resize event


window.addEventListener("resize", displayWindowSize);
</script>
Removing Event Listeners
You can use the removeEventListener() method to remove an event listener that have been
previously attached with the addEventListener(). Here's an example:

Example
Try this code »
<button id="myBtn">Click Me</button>

<script>
// Defining function
function greetWorld() {
alert("Hello World!");
}

// Selecting button element


var btn = document.getElementById("myBtn");

// Attaching event listener


btn.addEventListener("click", greetWorld);

// Removing event listener


btn.removeEventListener("click", greetWorld);
</script>

JavaScript Event Propagation


Understanding the Event Propagation
Event propagation is a mechanism that defines how events propagate or travel through the
DOM tree to arrive at its target and what happens to it afterward.

Let's understand this with the help of an example, suppose you have assigned a click event
handler on a hyperlink (i.e. <a> element) which is nested inside a paragraph (i.e. <p> element).
Now if you click on that link, the handler will be executed. But, instead of link, if you assign the
click event handler to the paragraph containing the link, then even in this case, clicking the
link will still trigger the handler. That's because events don't just affect the target element that
generated the event—they travel up and down through the DOM tree to reach their target.
This is known as event propagation

In modern browser event propagation proceeds in two phases: capturing,


and bubbling phase. Before we proceed further, take a look at the following illustration:
Above image demonstrates how event travels in the DOM tree during different phases of the
event propagation when an event is fired on an element that has parent elements.

The concept of event propagation was introduced to deal with the situations in which multiple
elements in the DOM hierarchy with a parent-child relationship have event handlers for the
same event, such as a mouse click. Now, the question is which element's click event will be
handled first when the user clicks on the inner element—the click event of the outer element,
or the inner element. In the following sections of this chapter we will discuss each phases of
the event propagation in greater detail and find out the answer of this question.

Note: Formally there are 3 phases, capture, target and bubble phase. But, the 2nd phase i.e.
the target phase (occurs when the event arrives at the target element that has generated the
event) is not handled separately in modern browsers, handlers registered for
both capturing and bubbling phases are executed in this phase.

The Capturing Phase


In the capturing phase, events propagate from the Window down through the DOM tree to
the target node. For example, if the user clicks a hyperlink, that click event would pass through
the <html> element, the <body> element, and the <p> element containing the link.

Also if any ancestor (i.e. parent, grandparent, etc.) of the target element and the target itself
has a specially registered capturing event listener for that type of event, those listeners are
executed during this phase. Let's check out the following example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Event Capturing Demo</title>
<style type="text/css">
div, p, a{
padding: 15px 30px;
display: block;
border: 2px solid #000;
background: #fff;
}
</style>
</head>
<body>
<div id="wrap">DIV
<p class="hint">P
<a href="#">A</a>
</p>
</div>

<script>
function showTagName() {
alert("Capturing: "+ this.tagName);
}

var elems = document.querySelectorAll("div, p, a");


for(let elem of elems) {
elem.addEventListener("click", showTagName, true);
}
</script>
</body>
</html>
Here is a simple demonstration that we've created utilizing the above example to show you
how event capturing works. Click on any element and observe in which order alert pop-ups
appears.

<div id="wrap">

<p class="hint"><a href="#">Click Me</a></p>


</div>

Event capturing is not supported in all browsers and rarely used. For instance, Internet
Explorer prior to version 9.0 does not support event capturing.

Also, event capturing only works with event handlers registered with
the addEventListener() method when the third argument is set to true. The traditional
method of assigning event handlers, like using onclick, onmouseover, etc. won't work here.
Please check out the JavaScript event listeners chapter to learn more about event listeners.
The Bubbling Phase
In the bubbling phase, the exact opposite occurs. In this phase event propagates or bubbles
back up the DOM tree, from the target element up to the Window, visiting all of the ancestors
of the target element one by one. For example, if the user clicks a hyperlink, that click event
would pass through the <p> element containing the link, the <body> element,
the <html> element, and the document node.

Also, if any ancestor of the target element and the target itself has event handlers assigned
for that type of event, those handlers are executed during this phase. In modern browsers, all
event handlers are registered in the bubbling phase, by default. Let's check out an example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Event Bubbling Demo</title>
<style type="text/css">
div, p, a{
padding: 15px 30px;
display: block;
border: 2px solid #000;
background: #fff;
}
</style>
</head>
<body>
<div onclick="alert('Bubbling: ' + this.tagName)">DIV
<p onclick="alert('Bubbling: ' + this.tagName)">P
<a href="#" onclick="alert('Bubbling: ' + this.tagName)">A</a>
</p>
</div>
</body>
</html>
Here is a simple demonstration that we've created utilizing the above example to show you
how event bubbling works. Click on any element and observe in which order alert pop-ups
appears.
<div id="wrap">

<p class="hint"><a href="#">Click Me</a></p>


</div>

Event bubbling is supported in all browsers, and it works for all handlers, regardless of how
they are registered e.g. using onclick or addEventListener() (unless they are registered
as capturing event listener). That's why the term event propagation is often used as a
synonym of event bubbling.

Accessing the Target Element


The target element is the DOM node that has generated the event. For example, if the user
clicks a hyperlink, the target element is the hyperlink.

The target element is accessible as event.target, it doesn't change through the event
propagation phases. Additionally, the this keyword represents the current element (i.e. the
element that has a currently running handler attached to it). Let's check out an example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Event Target Demo</title>
<style type="text/css">
div, p, a{
padding: 15px 30px;
display: block;
border: 2px solid #000;
background: #fff;
}
</style>
</head>
<body>
<div id="wrap">DIV
<p class="hint">P
<a href="#">A</a>
</p>
</div>

<script>
// Selecting the div element
var div = document.getElementById("wrap");

// Attaching an onclick event handler


div.onclick = function(event) {
event.target.style.backgroundColor = "lightblue";

// Let the browser finish rendering of background color before


showing alert
setTimeout(() => {
alert("target = " + event.target.tagName + ", this = " +
this.tagName);
event.target.style.backgroundColor = ''
}, 0);
}
</script>
</body>
</html>
Here is a simple demonstration that we've created utilizing the above example. Click on any
element and it will show you the tag name of the target element and the current element.

<div id="wrap">

<p class="hint"><a href="#">Click Me</a></p>


</div>

The fat arrow (=>) sign we've used in the example above is an arrow function expression. It has
a shorter syntax than a function expression, and it would make the this keyword behave
properly. Please check out the tutorial on ES6 features to learn more about arrow function.

Stopping the Event Propagation


You can also stop event propagation in the middle if you want to prevent any ancestor
element's event handlers from being notified about the event.

For example, suppose you have nested elements and each element has onclick event handler
that displays an alert dialog box. Normally, when you click on the inner element all handlers
will be executed at once, since event bubble up to the DOM tree.

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Event Propagation Demo</title>
<style type="text/css">
div, p, a{
padding: 15px 30px;
display: block;
border: 2px solid #000;
background: #fff;
}
</style>
</head>
<body>
<div id="wrap">DIV
<p class="hint">P
<a href="#">A</a>
</p>
</div>
<script>
function showAlert() {
alert("You clicked: "+ this.tagName);
}

var elems = document.querySelectorAll("div, p, a");


for(let elem of elems) {
elem.addEventListener("click", showAlert);
}
</script>
</body>
</html>
Here's a simple demonstration that we've created utilizing the above example. If you click on
any child element, event handler on parent elements are also executed and you may see
multiple alert boxes.

<div id="wrap">

<p class="hint"><a href="#">Click Me</a></p>


</div>

To prevent this situation you can stop event from bubbling up the DOM tree using
the event.stopPropagation() method. In the following example click event listener on the
parent elements will not execute if you click on the child elements.

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Stop Event Propagation Demo</title>
<style type="text/css">
div, p, a{
padding: 15px 30px;
display: block;
border: 2px solid #000;
background: #fff;
}
</style>
</head>
<body>
<div id="wrap">DIV
<p class="hint">P
<a href="#">A</a>
</p>
</div>

<script>
function showAlert(event) {
alert("You clicked: "+ this.tagName);
event.stopPropagation();
}

var elems = document.querySelectorAll("div, p, a");


for(let elem of elems) {
elem.addEventListener("click", showAlert);
}
</script>
</body>
</html>
Here's is the updated demonstration. Now if you click on any child element only one alert will
appear.
<div id="wrap">

<p class="hint"><a href="#">Click Me</a></p>


</div>

Additionally, you can even prevent any other listeners attached to the same element for the
same event type from being executed using the stopImmediatePropagation() method.

In the following example we've attached multiple listeners to the hyperlink, but only one
listener for the hyperlink will execute when you click the link, and you will see only one alert.

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Stop Immediate Propagation Demo</title>
<style type="text/css">
div, p, a{
padding: 15px 30px;
display: block;
border: 2px solid #000;
background: #fff;
}
</style>
</head>
<body>
<div onclick="alert('You clicked: ' + this.tagName)">DIV
<p onclick="alert('You clicked: ' + this.tagName)">P
<a href="#" id="link">A</a>
</p>
</div>

<script>
function sayHi() {
alert("Hi, there!");
event.stopImmediatePropagation();
}
function sayHello() {
alert("Hello World!");
}

// Attaching multiple event handlers to hyperlink


var link = document.getElementById("link");
link.addEventListener("click", sayHi);
link.addEventListener("click", sayHello);
</script>
</body>
</html>
Note: If several listeners are attached to the same element for the same event type, they are
executed in order in which they have been added. But, if any listener calls
the event.stopImmediatePropagation() method, no remaining listeners will be executed.

Preventing the Default Action


Some events have a default action associated with them. For example, if you click on a link
browser takes you to the link's target, when you click on a form submit button browser submit
the form, etc. You can prevent such default actions with the preventDefault() method of the
event object.

However, preventing the default actions does not stop event propagation; the event
continues to propagate to the DOM tree as usual. Here's is an example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Prevent Default Demo</title>
</head>
<body>
<form action="/examples/html/action.php" method="post" id="users">
<label>First Name:</label>
<input type="text" name="first-name" id="firstName">
<input type="submit" value="Submit" id="submitBtn">
</form>

<script>
var btn = document.getElementById("submitBtn");

btn.addEventListener("click", function(event) {
var name = document.getElementById("firstName").value;
alert("Sorry, " + name + ". The preventDefault() won't let you
submit this form!");
event.preventDefault(); // Prevent form submission
});
</script>
</body>
</html>

JavaScript Borrowing Methods


Borrowing Methods from Objects
In JavaScript, you can borrow methods from other objects to build some functionality without
inheriting all their properties and methods.

JavaScript provides two methods for all function objects, call() and apply(), that allow a
function to be invoked as if it were a method of another object. Here's an example:

Example
Try this code »
var objA = {
name: "object A",
say: function(greet) {
alert(greet + ", " + this.name);
}
}

objA.say("Hi"); // Displays: Hi, object A

var objB = {
name: "object B"
}

/* The objB doesn't have say() method, but it can borrow it from objA */
objA.say.call(objB, "Hello"); // Displays: Hello, object B

Difference Between call() and apply() Methods


The syntax of the apply() method is almost identical to call(), the only difference is,
the call() method takes a list of arguments like call(thisObj, arg1, arg2, ...), while
the apply() method takes a single array of arguments like apply(thisObj, [argsArray]).

Notice the square brackets ([]), which denotes an array, in the last line of the following
example:
Example
Try this code »
var objA = {
name: "object A",
say: function(greet) {
alert(greet + ", " + this.name);
}
}

objA.say("Hi"); // Displays: Hi, object A

var objB = {
name: "object B"
}

/* The objB doesn't have say() method, but it can borrow it from objA */
objA.say.apply(objB, ["Hello"]); // Displays: Hello, object B

Using Built-in Methods


The apply() method also allows you to use built-in methods for performing some tasks quickly
and easily. One such example is using the Math.max()/Math.min() to find out the maximum or
minimum value in an array, that would otherwise require looping over the array values.

As you already know from the previous chapters JavaScript arrays do not have a max() method,
but Math has, so we can apply the Math.max() method, like this:

Example
Try this code »
var numbers = [2, 5, 6, 4, 3, 7];

// Using Math.max apply


var max = Math.max.apply(null, numbers);
alert(max); // Outputs: 7
Note: The first argument to both call() and apply() is the object on which the function is to
be invoked. Using null as the first argument is like calling the function without providing any
object for the this pointer inside the function.

The new ES6 spread operator provides a shorter way to obtain the maximum or minimum value
from an array without using the apply() method. Here's an example:

Example
Try this code »
var numbers = [2, 5, 6, 4, 3, 7];
// Using spread operator
var max = Math.max(...numbers);
alert(max); // Outputs: 7
However, both spread (...) and apply() will either fail or return the incorrect result if the array
has too many elements (e.g. tens of thousands). In that case you can use the Array.reduce() to
find the maximum or minimum value in a numeric array, by comparing each value, like this:

Example
Try this code »
var numbers = [2, 5, 6, 4, 3, 7];

// Using reduce method


var max = numbers.reduce(function(a, b) {
return Math.max(a, b);
});
alert(max); // Outputs: 7

What is Hoisting
In JavaScript, all variable and function declarations are moved or hoisted to the top of their
current scope, regardless of where it is defined. This is the default behavior of JavaScript
interpreter which is called hoisting. In the following sections we'll take a closer look at how it
actually works.

Function Hoisting
Functions that are defined using a function declaration are automatically hoisted. That means
they can be called before they have been defined. Let's understand this with an example:

Example
Try this code »
// Calling function before declaration
sayHello(); // Outputs: Hello, I'm hoisted!

function sayHello() {
alert("Hello, I'm hoisted!");
}
As you can see, we've called the sayHello() function before it is defined, but the code still
works. This is because the function declaration is hoisted to the top automatically behind the
scenes.
Variable Hoisting
Similarly, the variable declarations are also hoisted to the top of their current scope
automatically. This means that if the variable is declared inside a function block, it will be
moved at the top of the function, but if it is declared outside any function it will be moved to
top of the script and become globally available. Take a look at the following example, to see
how this works:

Example
Try this code »
str = "Hello World!";
alert(str); // Outputs: Hello World!
var str;
However, JavaScript only hoists declarations, not initializations. That means if a variable is
declared and initialized after using it, the value will be undefined. For example:

Example
Try this code »
alert(str); // Outputs: undefined
var str;
str = "Hello World!";
Here's another example demonstrating the variable hoisting behavior of JavaScript:

Example
Try this code »
var i = 1; // Declare and initialize i
alert(i + ", " + j); // Outputs: 1, undefined
var j = 2; // Declare and initialize j

var x = 5; // Declare and initialize x


var y; // Declare y
alert(x + ", " + y); // Outputs: 5, undefined
y = 10; // Initialize y

var a = 3; // Declare and initialize a


b = 6; // Initialize b
alert(a + ", " + b); // Outputs: 3, 6
var b; // Declare b

var u = 4; // Declare and initialize u


alert(u + ", " + v); // Outputs: 4, undefined
var v; // Declare v
v = 8; // Initialize v
Variable hoisting may seem a little bit confusing at first glance, but if you go through these
examples carefully you will easily understand how it works.

Note: It is considered best practice to declare your variables at the top of the current scope,
because of hoisting behavior. Also, using a variable without declaring is not allowed
in JavaScript strict mode. See the next chapter to learn more about the strict mode.

JavaScript Closures
Understanding the JavaScript Closures
In the JavaScript functions chapter you've learnt that in JavaScript a variable's scope can
be global or local. Since ES6 you can also create block-scoped variables using the let keyword.

A global variable can be accessed and manipulated anywhere in the program, whereas a local
variable can only be accessed and manipulated by the function they are declared in.

However, there are certain situations when you want a variable to be available throughout the
script, but you don't want just any part of your code to be able to change its value accidently.

Let's see what happens if you try to achieve this using the global variable:

Example
Try this code »
// Global variable
var counter = 0;

// A function dedicated to manipulate the 'counter' variable


function makeCounter() {
return counter += 1;
}

// Calling the function


makeCounter();
console.log(counter); // Prints: 1

makeCounter();
console.log(counter); // Prints: 2

// Trying to manipulate the 'counter' variable from outside


counter = 10;
console.log(counter); // Prints: 10
As you can see in the above example, the value of the counter variable can be changed from
anywhere in the program, without calling the makeCounter() function (line no-17).

Now, let's try to achieve the same thing with the local variable and see what happens:
Example
Try this code »
function makeCounter() {
// Local variable
var counter = 0;

// Manipulating the 'counter' variable


return counter += 1;
}

// Calling the function


console.log(makeCounter()); // Prints: 1
console.log(makeCounter()); // Prints: 1
In this case the counter variable cannot be manipulated from outside, since it is local
to makeCounter() function, but its value will also not increase after subsequent function call,
because every time we call the function it reset the counter variable value, which you can
clearly see in the above example (line no-11). The JavaScript closure can solve our problem.

A closure is basically an inner function that has access to the parent function's scope, even
after the parent function has finished executing. This is accomplished by creating a function
inside another function. Let's take a look at the following example to see how it works:

Example
Try this code »
function makeCounter() {
var counter = 0;

// Nested function
function make() {
counter += 1;
return counter;
}
return make;
}

/* Execute the makeCounter() function and store the


returned value in the myCounter variable */
var myCounter = makeCounter();

console.log(myCounter()); // Prints: 1
console.log(myCounter()); // Prints: 2
As you can see in the above example, the inner function make() is returned from the outer
function makeCounter(). So the value of the myCounter is the inner make() function (line no-
14), and calling myCounter effectively calls make(). In JavaScript functions can assigned to
variables, passed as arguments to other functions, can be nested inside other functions, and
more. You'll also notice that the inner function make() is still able to access the value
of counter variable defined in the outer function, even though the makeCounter() function
has already finished executing (line no-14). It happens because functions in JavaScript form
closures. Closures internally store references to their outer variables, and can access and update
their values.

In the example above, the make() function is a closure whose code refers to the outer
variable counter. This implies that whenever the make() function is invoked, the code inside it
is able to access and update the counter variable because it is stored in the closure.

Finally, since the outer function has finished executing, no other part of the code can access or
manipulate the counter variable. Only the inner function has exclusive access to it.

The previous example can also be written using anonymous function expression, like this:

Example
Try this code »
// Anonymous function expression
var myCounter = (function() {
var counter = 0;

// Nested anonymous function


return function() {
counter += 1;
return counter;
}
})();

console.log(myCounter()); // Prints: 1
console.log(myCounter()); // Prints: 2
Tip: In JavaScript, all functions have access to the global scope, as well as the scope above
them. As JavaScript supports nested functions, this typically means that the nested functions
have access to any value declared in a higher scope including its parent function's scope.

Note: The global variables live as long as your application (i.e. your web page) lives. Whereas,
the local variables have a short life span, they are created when the function is invoked, and
destroyed as soon as the function is finished executing.

Creating the Getter and Setter Functions


Here we will create a variable secret and protect it from being directly manipulated from
outside code using closure. We will also create getter and setter functions to get and set its
value.

Additionally, the setter function will also perform a quick check whether the specified value is
a number or not, and if it is not it will not change the variable value.
Example
Try this code »
var getValue, setValue;

// Self-executing function
(function() {
var secret = 0;

// Getter function
getValue = function() {
return secret;
};

// Setter function
setValue = function(x) {
if(typeof x === "number") {
secret = x;
}
};
}());

// Calling the functions


getValue(); // Returns: 0
setValue(10);
getValue(); // Returns: 10
setValue(null);
getValue(); // Returns: 10
Tip: Self-executing functions are also called immediately invoked function expression
(IIFE), immediately executed function, or self-executing anonymous function.

JavaScript Strict Mode. What is Strict Mode


The strict mode was introduced in ECMAScript 5 (ES5). It is a semantically stricter or restricted
version of JavaScript language that produces errors for those mistakes that are handled
silently otherwise. For example, in non-strict mode if you initialize a variable without declaring
it using the var keyword (e.g. x = 5;), JavaScript interpreter will assume that you were referring
to a global variable and if no such variable existed, it will automatically create one.

Also, features that are deprecated may also generate errors in strict mode. Hence, strict mode
reduces bugs, improves security and overall performance of your application.

Enabling Strict Mode


To enable strict mode all you need to do is just add the string "use strict" at the beginning of
your script, as shown in the following example:
Example
Try this code »
"use strict";

// All your code goes here


x = 5; // ReferenceError: x is not defined
console.log(x);
If you add the "use strict" directive as the first line of your JavaScript program, strict mode
applies to the entire script. But, you can also turn on strict mode only within a function, like
this:

Example
Try this code »
x = 5;
console.log(x); // 5

function sayHello() {
"use strict";
str = "Hello World!"; // ReferenceError: str is not defined
console.log(str);
}
sayHello();
Note: The "use strict" directive is only recognized at the beginning of a script or a function.
All modern browsers support "use strict" directive except Internet Explorer 9 and lower
versions. Additionally, the browsers that don't support the "use strict" directive silently ignore
it and parse the JavaScript in non-strict mode.

General Restrictions in Strict Mode


Strict mode changes both syntax and runtime behavior. In the following sections, we will look
at the general restrictions that are enforced in the strict mode:

Undeclared Variables are Not Allowed


As you already know, in strict mode, all variables must be declared. if you assign a value to an
identifier that is not a declared variable, a ReferenceError will be thrown.

Example
Try this code »
"use strict";
function doSomething() {
msg = "Hi, there!"; // ReferenceError: msg is not defined
return msg;
}
console.log(doSomething());

Deleting a Variable or a Function is Not Allowed


In strict mode, if you try to delete a variable or a function, a syntax error will be thrown.
Whereas, in non-strict mode, such attempt fails silently and the delete expression evaluates
to false.

Example
Try this code »
"use strict";

var person = {name: "Peter", age: 28};


delete person; // SyntaxError
Similarly, when you try to delete a function in strict mode you will get an syntax error:

Example
Try this code »
"use strict";

function sum(a, b) {
return a + b;
}
delete sum; // SyntaxError

Duplicating a Parameter Name is Not Allowed


In strict mode, a syntax error will be thrown, if a function declaration has two or more
parameters with the same name. In non-strict mode, no error occurs.

Example
Try this code »
"use strict";

function square(a, a) { // SyntaxError


return a * a;
}
console.log(square(2, 2));
The eval Method Cannot Alter Scope
In strict mode, for security reasons, code passed to eval() cannot declare/modify variables or
define functions in the surrounding scope as it can in non-strict mode.

Example
Try this code »
"use strict";

eval("var x = 5;");
console.log(x); // ReferenceError: x is not defined

The eval and arguments Cannot be Used as Identifiers


In strict mode, the names eval and arguments are treated like keywords, so they cannot be used
as variable names, function names, or as function parameter names, etc.

Example
Try this code »
"use strict";

var eval = 10; // SyntaxError


console.log(eval);

The with Statement is Not Allowed


In strict mode, the with statement is not allowed. The with statement adds the properties and
methods of the object to the current scope. So, the statements nested inside
the with statement can call the properties and methods of the object directly without referring
it.

Example
Try this code »
"use strict";

// Without with statement


var radius1 = 5;
var area1 = Math.PI * radius1 * radius1;

// Using with statement


var radius2 = 5;
with(Math) { // SyntaxError
var area2 = PI * radius2 * radius2;
}
Writing to a Read-only Property is Not Allowed
In strict mode, assigning value to a non-writable property, a get-only property or a non-
existing property will throw an error. In non-strict mode, these attempts fail silently.

Example
Try this code »
"use strict";

var person = {name: "Peter", age: 28};

Object.defineProperty(person, "gender", {value: "male", writable: false});


person.gender = "female"; // TypeError

Adding a New Property to a Non-extensible Object is Not Allowed


In strict mode, attempts to create new properties on non-extensible or non-existing objects
will also throw an error. But in non-strict mode, these attempts fail silently.

Example
Try this code »
"use strict";

var person = {name: "Peter", age: 28};

console.log(Object.isExtensible(person)); // true
Object.freeze(person); // lock down the person object
console.log(Object.isExtensible(person)); // false
person.gender = "male"; // TypeError

Octal Numbers are Not Allowed


In strict mode, octal numbers (numbers prefixed with a zero e.g. 010, 0377) are not allowed.
Though, it is supported in all browsers in non-strict mode. However, in ES6 octal numbers are
supported by prefixing a number with 0o i.e. 0o10, 0o377, etc.

Example
Try this code »
"use strict";

var x = 010; // SyntaxError


console.log(parseInt(x));
You can clearly see in the above examples how strict mode can help you prevent making
common mistakes that often go unnoticed while writing a JavaScript program.
Keywords Reserved for Future are Not Allowed
As you already know from the previous chapters, the reserved words cannot be used as
identifier (variable names, function names, and loop labels) in a JavaScript program. In
addition to that the strict mode also imposes restrictions on uses of those keywords that are
reserved for future.

As per the latest ECMAScript 6 (or ES6) standards, these keywords are reserved keywords
when they are found in strict mode
code: await, implements, interface, package, private, protected, public, and static. However, for
optimal compatibility you should avoid using the reserved keywords as variable names or
function names in your program.

Tip: Reserved words, which are also called keywords, are special words that are part of the
JavaScript language syntax, for example, var, if, for, function, etc. See the JS reserved keywords
reference for a complete list of all reserved words in JavaScript.

JavaScript JSON Parsing


What is JSON
JSON stands for JavaScript Object Notation. JSON is extremely lightweight data-interchange
format for data exchange between server and client which is quick and easy to parse and
generate.

Like XML, JSON is also a text-based format that's easy to write and easy to understand for
both humans and computers, but unlike XML, JSON data structures occupy less bandwidth
than their XML versions. JSON is based on two basic structures:

 Object: This is defined as an unordered collection of key/value pairs (i.e. key:value).


Each object begins with a left curly bracket { and ends with a right curly bracket }. Multiple
key/value pairs are separated by a comma ,.
 Array: This is defined as an ordered list of values. An array begins with a left
bracket [ and ends with a right bracket ]. Values are separated by a comma ,.

In JSON, property names or keys are always strings, while the value can be
a string, number, true or false, null or even an object or an array. Strings must be enclosed in
double quotes " and can contain escape characters such as \n, \t and \. A JSON object may
look like this:

Example
Try this code »
{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"genre": "Fantasy Fiction",
"bestseller": true
}
}
Whereas an example of JSON array would look something like this:

Example
Try this code »
{
"fruits": [
"Apple",
"Banana",
"Strawberry",
"Mango"
]
}
Tip: A data-interchange format is a text format which is used to interchange or exchange data
between different platforms and operating systems. JSON is the most popular and lightweight
data-interchange format for web applications.

Parsing JSON Data in JavaScript


In JavaScript, you can easily parse JSON data received from the web server using
the JSON.parse() method. This method parses a JSON string and constructs the JavaScript value
or object described by the string. If the given string is not valid JSON, you will get a syntax
error.

Let's suppose we've received the following JSON-encoded string from a web server:

Example
Try this code »
{"name": "Peter", "age": 22, "country": "United States"}
Now, we can simply use the JavaScript JSON.parse() method to convert this JSON string into a
JavaScript object and access individual values using the dot notation ( .), like this:

Example
Try this code »
// Store JSON data in a JS variable
var json = '{"name": "Peter", "age": 22, "country": "United States"}';

// Converting JSON-encoded string to JS object


var obj = JSON.parse(json);

// Accessing individual value from JS object


alert(obj.name); // Outputs: Peter
alert(obj.age); // Outputs: 22
alert(obj.country); // Outputs: United States
Please check out the tutorial on PHP JSON parsing to learn, how to return JSON data from a
web server in response, as well as, how to encode/decode JSON data on server side using
PHP.

Parsing Nested JSON Data in JavaScript


JSON objects and arrays can also be nested. A JSON object can arbitrarily contains other JSON
objects, arrays, nested arrays, arrays of JSON objects, and so on. The following example will
show you how to parse a nested JSON object and extract all the values in JavaScript.

Example
Try this code »
/* Storing multi-line JSON string in a JS variable
using the new ES6 template literals */
var json = `{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
"genre": "Fantasy Fiction",
"price": {
"paperback": "$10.40", "hardcover": "$20.32", "kindle":
"$4.11"
}
}
}`;

// Converting JSON object to JS object


var obj = JSON.parse(json);

// Define recursive function to print nested values


function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(obj[k] + "<br>");
};
}
};

// Printing all the values from the resulting object


printValues(obj);

document.write("<hr>");

// Printing a single value


document.write(obj["book"]["author"] + "<br>"); // Prints: J. K. Rowling
document.write(obj["book"]["characters"][0] + "<br>"); // Prints: Harry
Potter
document.write(obj["book"]["price"]["hardcover"]); // Prints: $20.32

Encoding Data as JSON in JavaScript


Sometimes JavaScript object or value from your code need to be transferred to the server
during an Ajax communication. JavaScript provides JSON.stringify() method for this purpose
which converts a JavaScript value to a JSON string, as shown below:

Stringify a JavaScript Object


The following example will show you how to convert a JavaScript object to JSON string:

Example
Try this code »
// Sample JS object
var obj = {"name": "Peter", "age": 22, "country": "United States"};

// Converting JS object to JSON string


var json = JSON.stringify(obj);
alert(json);
The output of the above example will look something like this:

{"name":"Peter","age":22,"country":"United States"}

Note: Although, JavaScript and JSON objects look quite similar, but they are not exactly the
same. For example, in JavaScript, object property names can be enclosed in single quotes
('...') or double quotes ("..."), or you can omit the quotes altogether. But, in JSON, all
property names must be enclosed in double quotes.
Stringify a JavaScript Array
Similarly, you can convert the JavaScript arrays to JSON strings, like this:

Example
Try this code »
// Sample JS array
var arr = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Converting JS array to JSON string


var json = JSON.stringify(arr);
alert(json);
The output of the above example will look something like this:

["Apple","Banana","Mango","Orange","Papaya"]

Warning: Do not use eval() function to evaluate JSON data (e.g., including function
definitions in JSON string and converting them back into executable functions
with eval() method), as it allows attacker to inject malicious JavaScript code into your
application.

JavaScript Error Handling


Handling Errors
Sometimes your JavaScript code does not run as smooth as expected, resulting in an error.
There are a number of reasons that may cause errors, for instance:

 A problem with network connection


 A user might have entered an invalid value in a form field
 Referncing objects or functions that do not exist
 Incorrect data being sent to or received from the web server
 A service that the application needs to access might be temporarily unavailable

These types of errors are known as runtime errors, because they occur at the time the script
runs. A professional application must have the capabilities to handle such runtime error
gracefully. Usually this means informing the user about the problem more clearly and
precisely.
The try...catch Statement
JavaScript provides the try-catch statement to trap the runtime errors, and handle them
gracefully.

Any code that might possibly throw an error should be placed in the try block of the
statement, and the code to handle the error is placed in the catch block, as shown here:
try {
// Code that may cause an error
} catch(error) {
// Action to be performed when an error occurs
}

If an error occurs at any point in the try block, code execution immediately transferred from
the try block to the catch block. If no error occurs in the try block, the catch block will be
ignored, and the program will continue executing after the try-catch statement.

The following example demonstrates how the try-catch statement actually works:

Example
Try this code »
try {
var greet = "Hi, there!";
document.write(greet);

// Trying to access a non-existent variable


document.write(welcome);

// If error occurred following line won't execute


alert("All statements are executed successfully.");
} catch(error) {
// Handle the error
alert("Caught error: " + error.message);
}

// Continue execution
document.write("<p>Hello World!</p>");
The above script will generate an error that is displayed in an alert dialog box, instead of
printing it to browser console. Besides that, the program didn't stop abruptly even though an
error has occurred.

Also, note that the catch keyword is followed by an identifier in parentheses. This identifier is
act like a function parameter. When an error occurs, the JavaScript interpreter generates an
object containing the details about it. This error object is then passed as an argument
to catch for handling.
Tip: The try-catch statement is an exception handling mechanism. An exception is signal that
indicates that some sort of exceptional condition or error has occurred during the execution
of a program. The terms "exception" and "error" are often used interchangeably.

The try...catch...finally Statement


The try-catch statement can also have a finally clause. The code inside the finally block will
always execute, regardless of whether an error has occurred in the try block or not.

The following example will always display the total time taken to complete the execution of
the code.

Example
Try this code »
// Assigning the value returned by the prompt dialog box to a variable
var num = prompt("Enter a positive integer between 0 to 100");

// Storing the time when execution start


var start = Date.now();

try {
if(num > 0 && num <= 100) {
alert(Math.pow(num, num)); // the base to the exponent power
} else {
throw new Error("An invalid value is entered!");
}
} catch(e) {
alert(e.message);
} finally {
// Displaying the time taken to execute the code
alert("Execution took: " + (Date.now() - start) + "ms");
}

Throwing Errors
So far we've seen the errors that are automatically thrown by JavaScript parser when an error
occurs. However, it is also possible to throw an error manually by using the throw statement.

The general form (or syntax) of the throw statement is: throw expression;

The expression can be a object or a value of any data type. However, it's better to use the
objects, preferably with name and message properties. The JavaScript built-in Error() constructor
provides a convenient way create an error object. Let's look at some examples:

Example
Try this code »
throw 123;
throw "Missing values!";
throw true;
throw { name: "InvalidParameter", message: "Parameter is not a number!" };
throw new Error("Something went wrong!");
Note: If you're using the JavaScript built-in error constructor functions
(e.g. Error(), TypeError(), etc.) for creating error objects, then the name property is same as the
name of the constructor, and the message is equal to the argument passed to the constructor
function.

Now we're going to create a function squareRoot() to find the square root of a number. This
can be done simply by using the JavaScript built-in function Math.sqrt(), but the problem here
is, it returns NaN for negative numbers, without providing any hint on what has gone wrong.

We're going to fix this problem by throwing a custom error if a negative number is supplied.

Example
Try this code »
function squareRoot(number) {
// Throw error if number is negative
if(number < 0) {
throw new Error("Sorry, can't calculate square root of a negative
number.");
} else {
return Math.sqrt(number);
}
}

try {
squareRoot(16);
squareRoot(625);
squareRoot(-9);
squareRoot(100);

// If error is thrown following line won't execute


alert("All calculations are performed successfully.");
} catch(e) {
// Handle the error
alert(e.message);
}
Tip: Theoretically it is possible to calculate the square root of negative number by using the
imaginary number i, where i2 = -1. Therefore square root of -4 is 2i, square root of -9 is 3i,
and so on. But imaginary numbers are not supported in JavaScript.
Error Types
The Error object is the base type of all errors and it has two main properties — a name property
that specifies the type of error, and a message property that holds a message describing the
error in more detail. Any error thrown will be an instance of the Error object.

There are several different types of error that can occur during the execution of a JavaScript
program, such as RangeError, ReferenceError, SyntaxError, TypeError, and URIError.

The following section describes each one of these error type in more detail:

RangeError
A RangeError is thrown when you use a number that is outside the range of allowable values.
For example, creating an array with a negative length will throw RangeError.

Example
Try this code »
var num = 12.735;
num.toFixed(200); // throws a range error (allowable range from 0 to 100)

var array = new Array(-1); // throws a range error

ReferenceError
A ReferenceError is typically thrown when you try to reference or access a variable or object
that doesn't exist. The following example shows how the ReferenceError occurs.

Example
Try this code »
var firstName = "Harry";
console.log(firstname); // throws a reference error (variable names are
case-sensitive)

undefinedObj.getValues(); // throws a reference error

nonexistentArray.length; // throws a reference error

SyntaxError
A SyntaxError is thrown at runtime if there is any syntax problem in your JavaScript code. For
example, if closing bracket is missing, loops are not structured properly, and so on.
Example
Try this code »
var array = ["a", "b", "c"];
document.write(array.slice(2); // throws a syntax error (missing bracket)

alert("Hello World!'); // throws a syntax error (quote mismatch)

TypeError
A TypeError is thrown when a value is not of the expected type. For example, calling a string
method on number, calling an array method on string, and so on.

Example
Try this code »
var num = 123;
num.toLowerCase(); /* throws a type error (since toLowerCase() is a string
method, a number can't be converted to lowercase) */

var greet = "Hello World!"


greet.join() // throws a type error (since join() is an array method)

URIError
A URIError is thrown when you specified an invalid URI (stands for Uniform Resource Identifier)
to the URI-related functions such as encodeURI() or decodeURI(), as shown here:

Example
Try this code »
var a = "%E6%A2%B";
decodeURI(a); // throws a URI error

var b = "\uD800";
encodeURI(b); // throws a URI error
Note: There is one more error type EvalError which is thrown when an error occurs during the
execution of code via eval() function. But, this error is not thrown by JavaScript anymore,
however this object still remains for backward compatibility.

The specific error type can also be thrown manually using their respective constructor and
the throw statement, e.g., to throw a TypeError you can use the TypeError() constructor, like this:

Example
Try this code »
var num = prompt("Please enter a number");

try {
if(num != "" && num !== null && isFinite(+num)) {
alert(Math.exp(num));
} else {
throw new TypeError("You have not entered a number.");
}
} catch(e) {
alert(e.name);
alert(e.message);
alert(e.stack); // non-standard property
}
Note: The Error object also supports some non-standard properties. One of the most widely
used such property is: stack, which returns the stack trace for that error. You can use it for
debugging purposes, but don't use it on production sites.

JavaScript Regular Expressions


What is Regular Expression
Regular Expressions, commonly known as "regex" or "RegExp", are a specially formatted text
strings used to find patterns in text. Regular expressions are one of the most powerful tools
available today for effective and efficient text processing and manipulations. For example, it
can be used to verify whether the format of data i.e. name, email, phone number, etc. entered
by the user is correct or not, find or replace matching string within text content, and so on.

JavaScript supports Perl style regular expressions. Why Perl style regular expressions? Because
Perl (Practical Extraction and Report Language) was the first mainstream programming
language that provided integrated support for regular expressions and it is well known for its
strong support of regular expressions and its extraordinary text processing and manipulation
capabilities.

Let's begin with a brief overview of the commonly used JavaScript's built-in methods for
performing pattern-matching before delving deep into the world of regular expressions.

Function What it Does

exec() Search for a match in a string. It returns an array of information or null on mismatch.

test() Test whether a string matches a pattern. It returns true or false.

search() Search for a match within a string. It returns the index of the first match, or -1 if not found.

replace() Search for a match in a string, and replaces the matched substring with a replacement string.
Function What it Does

match() Search for a match in a string. It returns an array of information or null on mismatch.

split() Splits up a string into an array of substrings using a regular expression.

Note: The methods exec() and test() are RegExp methods that takes a string as a
parameter, whereas the methods search(), replace(), match() and split() are String
methods that takes a regular expression as a parameter.

Defining Regular Expressions


In JavaScript, regular expressions are represented by RegExp object, which is a native
JavaScript object like String, Array, and so on. There are two ways of creating a new RegExp
object — one is using the literal syntax, and the other is using the RegExp() constructor.

The literal syntax uses forward slashes (/pattern/) to wrap the regular expression pattern,
whereas the constructor syntax uses quotes ("pattern"). The following example demonstrates
both ways of creating a regular expression that matches any string that begins with "Mr.".

Example
Run this code »
// Literal syntax
var regex = /^Mr\./;

// Constructor syntax
var regex = new RegExp("^Mr\\.");
As you can see, the regular expression literal syntax is shorter and easier to read. Therefore it
is preferable to use the literal syntax. We'll also use it throughout this tutorial.

Note: When using the constructor syntax, you've to double-escape special characters, which
means to match "." you need to write "\\." instead of "\.". If there is only one backslash, it
would be interpreted by JavaScript's string parser as an escaping character and removed.

Pattern Matching with Regular Expression


Regular expression patterns include the use of letters, digits, punctuation marks, etc., plus a
set of special regular expression characters (do not confuse with the HTML special characters).

The characters that are given special meaning within a regular expression, are:
. * ? + [ ] ( ) { } ^ $ | \. You will need to backslash these characters whenever you want to
use them literally. For example, if you want to match ".", you'd have to write \.. All other
characters automatically assume their literal meanings.
The following sections describe the various options available for formulating patterns:

Character Classes
Square brackets surrounding a pattern of characters are called a character class e.g. [abc]. A
character class always matches a single character out of a list of specified characters that
means the expression [abc] matches only a, b or c character.

Negated character classes can also be defined that match any character except those
contained within the brackets. A negated character class is defined by placing a caret (^)
symbol immediately after the opening bracket, like [^abc], which matches any character
except a, b, and c.

You can also define a range of characters by using the hyphen (-) character inside a character
class, like [0-9]. Let's look at some examples of the character classes:

RegExp What it Does

[abc] Matches any one of the characters a, b, or c.

[^abc] Matches any one character other than a, b, or c.

[a-z] Matches any one character from lowercase a to lowercase z.

[A-Z] Matches any one character from uppercase a to uppercase z.

[a-Z] Matches any one character from lowercase a to uppercase Z.

[0-9] Matches a single digit between 0 and 9.

[a-z0-9] Matches a single character between a and z or between 0 and 9.

The following example will show you how to find whether a pattern exists within a string or
not using the regular expression with the JavaScript test() method:

Example
Run this code »
var regex = /ca[kf]e/;
var str = "He was eating cake in the cafe.";

// Test the string against the regular expression


if(regex.test(str)) {
alert("Match found!");
} else {
alert("Match not found.");
}
Further, you can add the global flag g to a regular expression to find all matches in a string:

Example
Run this code »
var regex = /ca[kf]e/g;
var str = "He was eating cake in the cafe.";
var matches = str.match(regex);
alert(matches.length); // Outputs: 2
Tip: Regular expressions aren't exclusive to JavaScript. Languages such as Java, Perl, Python,
PHP, etc. use the same notation for finding patterns in text.

Predefined Character Classes


Some character classes such as digits, letters, and whitespaces are used so frequently that
there are shortcut names for them. The following table lists those predefined character
classes:

Shortcut What it Does

. Matches any single character except newline \n.

\d matches any digit character. Same as [0-9]

\D Matches any non-digit character. Same as [^0-9]

\s Matches any whitespace character (space, tab, newline or carriage return character).
Same as [ \t\n\r]

\S Matches any non-whitespace character.


Same as [^ \t\n\r]

\w Matches any word character (definned as a to z, A to Z,0 to 9, and the underscore).


Same as [a-zA-Z_0-9]

\W Matches any non-word character. Same as [^a-zA-Z_0-9]

The following example will show you how to find and replace space with a hyphen character
in a string using regular expression with the JavaScript replace() method:

Example
Run this code »
var regex = /\s/g;
var replacement = "-";
var str = "Earth revolves around\nthe\tSun";

// Replace spaces, newlines and tabs


document.write(str.replace(regex, replacement) + "<hr>");

// Replace only spaces


document.write(str.replace(/ /g, "-"));

Repetition Quantifiers
In the previous section we've learnt how to match a single character in a variety of fashions.
But what if you want to match on more than one character? For example, let's say you want to
find out words containing one or more instances of the letter p, or words containing at least
two p's, and so on.

This is where quantifiers come into play. With quantifiers you can specify how many times a
character in a regular expression should match. Quantifiers can be applied to the individual
characters, as well as classes of characters, and groups of characters contained by the
parentheses.

The following table lists the various ways to quantify a particular pattern:

RegExp What it Does

p+ Matches one or more occurrences of the letter p.

p* Matches zero or more occurrences of the letter p.

p? Matches zero or one occurrences of the letter p.

p{2} Matches exactly two occurrences of the letter p.

p{2,3} Matches at least two occurrences of the letter p, but not more than three occurrences.

p{2,} Matches two or more occurrences of the letter p.

p{,3} Matches at most three occurrences of the letter p

The regular expression in the following example will splits the string at comma, sequence of
commas, whitespace, or combination thereof using the JavaScript split() method:

Example
Run this code »
var regex = /[\s,]+/;
var str = "My favourite colors are red, green and blue";
var parts = str.split(regex);
// Loop through parts array and display substrings
for(var part of parts){
document.write("<p>" + part + "</p>");
}

Position Anchors
There are certain situations where you want to match at the beginning or end of a line, word,
or string. To do this you can use anchors. Two common anchors are caret ( ^) which represent
the start of the string, and the dollar ($) sign which represent the end of the string.

RegExp What it Does

^p Matches the letter p at the beginning of a line.

p$ Matches the letter p at the end of a line.

The regular expression in the following example will match only those names in the names
array which start with the letter "J" using the JavaScript test() function:

Example
Run this code »
var regex = /^J/;
var names = ["James Bond", "Clark Kent", "John Rambo"];

// Loop through names array and display matched names


for(var name of names) {
if(regex.test(name)) {
document.write("<p>" + name + "</p>")
}
}

Pattern Modifiers (Flags)


A pattern modifier allows you to control the way a pattern match is handled. Pattern modifiers
are placed directly after the regular expression, for example, if you want to search for a
pattern in a case-insensitive manner, you can use the i modifier, like this: /pattern/i.

The following table lists some of the most commonly used pattern modifiers.

Modifier What it Does

g Perform a global match i.e. finds all occurrences.


Modifier What it Does

i Makes the match case-insensitive manner.

m Changes the behavior of ^ and $ to match against a newline boundary (i.e. start or end of each line within a
multiline string), instead of a string boundary.

o Evaluates the expression only once.

s Changes the behavior of . (dot) to match all characters, including newlines.

x Allows you to use whitespace and comments within a regular expression for clarity.

The following example will show you how to use the g and i modifiers in a regular expression
to perform a global and case-insensitive search with the JavaScript match() method.

Example
Run this code »
var regex = /color/gi;
var str = "Color red is more visible than color blue in daylight.";
var matches = str.match(regex); // global, case-insensitive match
console.log(matches);
// expected output: ["Color", "color"]
Similarly, the following example shows how to match at the beginning of every line in a multi-
line string using the ^ anchor and m modifier with the JavaScript match() method.

Example
Run this code »
var regex = /^color/gim;
var str = "Color red is more visible than \ncolor blue in daylight.";
var matches = str.match(regex); // global, case-insensitive, multiline
match
console.log(matches);
// expected output: ["Color", "color"]

Alternation
Alternation allows you to specify alternative version of a pattern. Alternation in a regular
expression works just like the OR operator in an if-else conditional statement. You can
specify alternation using a vertical bar (|). For example, the regexp /fox|dog|cat/ matches
the string "fox", or the string "dog", or the string "cat". Here's an example:
Example
Run this code »
var regex = /fox|dog|cat/;
var str = "The quick brown fox jumps over the lazy dog.";
var matches = str.match(regex);
console.log(matches);
// expected output: ["fox", index: 16, ...]
Note: Alternatives are evaluated from left to right until a match is found. If the left alternative
matches, the right alternative is ignored completely even if it has a match.

Grouping
Regular expressions use parentheses to group subexpressions, just like mathematical
expressions. Parentheses allow a repetition quantifier to be applied to an entire
subexpression. E.g., in regexp /go+/ the quantifier + is applied only to the last character o and
it matches the strings "go", "goo", and so on. Whereas, in regexp /(go)+/ the quantifier + is
applied to the group of characters g and o and it matches the strings "go", "gogo", and so on.

Example
Run this code »
var regex = /(go)+/i;
var str = "One day Gogo will go to school.";
var matches = str.match(regex); // case-insensitive match
console.log(matches);
// expected output: ["Gogo", "go", index: 8, ...]
Note: If the string matches the pattern, the match() method returns an array containing the
entire matched string as the first element, followed by any results captured in parentheses,
and the index of the whole match. If no matches were found, it returns null.

Tip: If the regular expression includes the g flag, the match() method only returns an array
containing all matched substrings rather than match object. Captured groups, index of the
whole match, and other properties are not returned.

Word Boundaries
A word boundary character ( \b) helps you search for the words that begins and/or ends with
a pattern. For example, the regexp /\bcar/ matches the words beginning with the pattern car,
and would match cart, carrot, or cartoon, but would not match oscar. Similarly, the
regexp /car\b/ matches the words ending with the pattern car, and would match oscar or
supercar, but would not match cart. Likewise, the /\bcar\b/ matches the words beginning
and ending with the pattern car, and would match only the word car.

The following example will highlight the words beginning with car in bold:
Example
Run this code »
var regex = /(\bcar\w*)/g;
var str = "Words begining with car: cart, carrot, cartoon. Words ending
with car: oscar, supercar.";
var replacement = '<b>$1</b>';
var result = str.replace(regex, replacement);
document.write(result);

JavaScript Form Validation


Understanding Client-Side Validation
Web forms have become an essential part of web applications. It is often used to collect user's
information such as name, email address, location, age, and so on. But it is quite possible that
some user might not enter the data what you've expected. So to save bandwidth and avoid
unnecessary strain on your server resources you can validate the form data on client-side (i.e.
user's system) using JavaScript before passing it onto the web server for further processing.

Client-side validation is also helpful in creating better user experience, since it is faster
because validation occurs within the user's web browser, whereas server-side validation
occurs on the server, which require user's input to be first submitted and sent to the server
before validation occurs, also user has to wait for server response to know what exactly went
wrong.

In the following section we will take a closer look at how to perform JavaScript form validation
and handle any input errors found appropriately and gracefully.

Note: Client-side validation is not a substitute or alternative for server-side validation. You
should always validate form data on the server-side even if they are already validated on the
client-side, because user can disable JavaScript in their browser.

Form Validation with JavaScript


The form validation process typically consists of two parts— the required fields
validation which is performed to make sure that all the mandatory fields are filled in, and
the data format validation which is performed to ensure that the type and format of the data
entered in the form is valid. Well, let's get straight to it and see how this actually works.
Creating the HTML Form
Let's first create a simple HTML form that we will validate on client-side using JavaScript when
the user clicks on the submit button. Well, let's create an HTML file named "application-
form.html" and place the following code in it, then save it somewhere on your system.

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple HTML Form</title>
<link rel="stylesheet" href="style.css">
<script src="validator.js"></script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()"
action="confirmation.php" method="post">
<h2>Application Form</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="error" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="error" id="emailErr"></div>
</div>
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile" maxlength="10">
<div class="error" id="mobileErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Australia</option>
<option>India</option>
<option>United States</option>
<option>United Kingdom</option>
</select>
<div class="error" id="countryErr"></div>
</div>
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio" name="gender" value="male">
Male</label>
<label><input type="radio" name="gender" value="female">
Female</label>
</div>
<div class="error" id="genderErr"></div>
</div>
<div class="row">
<label>Hobbies <i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox" name="hobbies[]" value="sports">
Sports</label>
<label><input type="checkbox" name="hobbies[]" value="movies">
Movies</label>
<label><input type="checkbox" name="hobbies[]" value="music">
Music</label>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>

Building the Form Validation Script


Now we're going to create a JavaScript file that holds our complete validation script.

Well, let's create a JavaScript file named "validator.js" and place the following code inside it,
then save it at the same location where you've saved the previous HTML file. Go through each
line of the following example code to understand how JavaScript validation works:

Example
Try this code »
// Defining a function to display error message
function printError(elemId, hintMsg) {
document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form


function validateForm() {
// Retrieving the values of form elements
var name = document.contactForm.name.value;
var email = document.contactForm.email.value;
var mobile = document.contactForm.mobile.value;
var country = document.contactForm.country.value;
var gender = document.contactForm.gender.value;
var hobbies = [];
var checkboxes = document.getElementsByName("hobbies[]");
for(var i=0; i < checkboxes.length; i++) {
if(checkboxes[i].checked) {
// Populate hobbies array with selected values
hobbies.push(checkboxes[i].value);
}
}

// Defining error variables with a default value


var nameErr = emailErr = mobileErr = countryErr = genderErr = true;

// Validate name
if(name == "") {
printError("nameErr", "Please enter your name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if(regex.test(name) === false) {
printError("nameErr", "Please enter a valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}

// Validate email address


if(email == "") {
printError("emailErr", "Please enter your email address");
} else {
// Regular expression for basic email validation
var regex = /^\S+@\S+\.\S+$/;
if(regex.test(email) === false) {
printError("emailErr", "Please enter a valid email address");
} else{
printError("emailErr", "");
emailErr = false;
}
}

// Validate mobile number


if(mobile == "") {
printError("mobileErr", "Please enter your mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if(regex.test(mobile) === false) {
printError("mobileErr", "Please enter a valid 10 digit mobile
number");
} else{
printError("mobileErr", "");
mobileErr = false;
}
}

// Validate country
if(country == "Select") {
printError("countryErr", "Please select your country");
} else {
printError("countryErr", "");
countryErr = false;
}

// Validate gender
if(gender == "") {
printError("genderErr", "Please select your gender");
} else {
printError("genderErr", "");
genderErr = false;
}

// Prevent the form from being submitted if there are any errors
if((nameErr || emailErr || mobileErr || countryErr || genderErr) ==
true) {
return false;
} else {
// Creating a string from input data for preview
var dataPreview = "You've entered the following details: \n" +
"Full Name: " + name + "\n" +
"Email Address: " + email + "\n" +
"Mobile Number: " + mobile + "\n" +
"Country: " + country + "\n" +
"Gender: " + gender + "\n";
if(hobbies.length) {
dataPreview += "Hobbies: " + hobbies.join(", ");
}
// Display input data in a dialog box before submitting the form
alert(dataPreview);
}
};
The value of an individual form field can be accessed and retrieved using the
syntax document.formName.fieldName.value or document.getElementsByName(name).value. But, to get
the values from a form field that supports multiple selections, like a group of checkboxes, you
need to utilize the loop statement as shown in the example above (line no-14 to 21).

Also, to check whether the format of input data is correct or not we've used the regular
expressions. It is one of the most effective techniques for validating the user inputs.

Furthermore, the above script will also display the data entered by the user in an alert dialog
box for preview purpose before submitting the form to the web server.

Tip: However, you can validate email format using regular expression. But a user might enter
an email that is correctly formatted but does not exist. So for authentic email validation, send
confirmation email to the user and verify whether the email really exists or not.
Adding Style Sheet to Beautify the Form
Finally, create the file named "style.css" and place the following code in it, then save it also at
the same location where you've saved the previous two files. These are the style rules to
beautify our form.

Example
Try this code »
body {
font-size: 16px;
background: #f9f9f9;
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
form {
width: 300px;
background: #fff;
padding: 15px 40px 40px;
border: 1px solid #ccc;
margin: 50px auto 0;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px
}
label i {
color: #999;
font-size: 80%;
}
input, select {
border: 1px solid #ccc;
padding: 10px;
display: block;
width: 100%;
box-sizing: border-box;
border-radius: 2px;
}
.row {
padding-bottom: 10px;
}
.form-inline {
border: 1px solid #ccc;
padding: 8px 10px 4px;
border-radius: 2px;
}
.form-inline label, .form-inline input {
display: inline-block;
width: auto;
padding-right: 15px;
}
.error {
color: red;
font-size: 90%;
}
input[type="submit"] {
font-size: 110%;
font-weight: 100;
background: #006dcc;
border-color: #016BC1;
box-shadow: 0 3px 0 #0165b6;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #0165b6;
}

JavaScript Cookies. What is a Cookie


A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the
user's computer. They are typically used for keeping track of information such as user
preferences that the site can retrieve to personalize the page when user visits the website next
time.

Cookies are an old client-side storage mechanism that was originally designed for use by
server-side scripting languages such as PHP, ASP, etc. However, cookies can also be created,
accessed, and modified directly using JavaScript, but the process is little bit complicated and
messy.

Tip: A cookie can be up to 4 KB, including its name and values, cookies that exceed this
length are trimmed to fit. Also, each time the browser requests a page to the server, all the
data in the cookie is automatically sent to the server within the request.

Warning: Don't store sensitive data such as a password or credit card information in cookies
since it could potentially be manipulated by the malicious user.

Creating a Cookie in JavaScript


In JavaScript, you can create, read, and delete cookies with the document.cookie property. This
property represents all the cookies associated with a document.

To create or store a new cookie, assign a name=value string to this property, like this:
document.cookie = "firstName=Christopher";
A cookie value cannot contain semicolons, commas, or spaces. For this reason, you will need
to use the JavaScript's built-in function encodeURIComponent() to encode the values containing
these characters before storing it in the cookie. Likewise, you'll need to use the
corresponding decodeURIComponent() function when you read the cookie value.
document.cookie = "name=" + encodeURIComponent("Christopher Columbus");

By default, the lifetime of a cookie is the current browser session, which means it is lost when
the user exits the browser. For a cookie to persist beyond the current browser session, you will
need to specify its lifetime (in seconds) with a max-age attribute. This attribute determine how
long a cookie can be remain on the user's system before it is deleted, e.g., following cookie
will live for 30 days.
document.cookie = "firstName=Christopher; max-age=" + 30*24*60*60;

You can also specify the lifetime of a cookie with the expires attribute. This attribute takes an
exact date (in GMT/UTC format) when the cookie should expire, rather than an offset in
seconds.
document.cookie = "firstName=Christopher; expires=Thu, 31 Dec 2099 23:59:59 GMT";

Here's a function that sets a cookie with an optional max-age attribute. You can also use the
same function to delete a cookie by passing the value 0 for daysToLive parameter.

Example
Try this code »
function setCookie(name, value, daysToLive) {
// Encode value in order to escape semicolons, commas, and whitespace
var cookie = name + "=" + encodeURIComponent(value);

if(typeof daysToLive === "number") {


/* Sets the max-age attribute so that the cookie expires
after the specified number of days */
cookie += "; max-age=" + (daysToLive*24*60*60);

document.cookie = cookie;
}
}
By default, a cookie is available to all web pages in the same directory or any subdirectories of
that directory. However, if you specify a path the cookie is available to all web pages in the
specified path and to all web pages in all subdirectories of that path. For example, if the path
is set to / the cookie is available throughout a website, regardless of which page creates the
cookie.
document.cookie = "firstName=Christopher; path=/";
Further, you can use the domain attribute if you want a cookie to be available across
subdomains. By default, cookies are available only to the pages in the domain they were set
in.

If a cookie created by a page on blog.example.com sets its path attribute to / and


its domain attribute to example.com, that cookie is also available to all web pages
on backend.example.com, portal.example.com. However, you cannot share cookies outside of a
domain.
document.cookie = "firstName=Christopher; path=/; domain=example.com";

There is also a boolean attribute named secure. If this attribute is specified, the cookie will be
only be transmitted over a secure (i.e. encrypted) connection such as HTTPS.
document.cookie = "firstName=Christopher; path=/; domain=example.com; secure";

Reading a Cookie
Reading a cookie is a slightly more complex because the document.cookie property simply
returns a string containing a semicolon and a space separated list of all cookies
(i.e. name=value pairs, for example, firstName=John; lastName=Doe;). This string doesn't contain
the attributes such as expires, path, domain, etc. that may have been set for the cookie.

In order to get the individual cookie from this list, you need to make use of split() method to
break it into individual name=value pairs, and search for the specific name, as shown below:

Example
Try this code »
function getCookie(name) {
// Split cookie string and get all individual name=value pairs in an
array
var cookieArr = document.cookie.split(";");

// Loop through the array elements


for(var i = 0; i < cookieArr.length; i++) {
var cookiePair = cookieArr[i].split("=");

/* Removing whitespace at the beginning of the cookie name


and compare it with the given string */
if(name == cookiePair[0].trim()) {
// Decode the cookie value and return
return decodeURIComponent(cookiePair[1]);
}
}

// Return null if not found


return null;
}
Now we're going to create one more function checkCookie() that will check whether
the firstName cookie is set or not by utilizing the above getCookie() function, and if it is set then
this function will display a greeting message, and if it is not then this function will prompt user
to enter their first name and store it in the cookie using our previously
created setCookie() function.

Example
Try this code »
function checkCookie() {
// Get cookie using our custom function
var firstName = getCookie("firstName");

if(firstName != "") {
alert("Welcome again, " + firstName);
} else {
firstName = prompt("Please enter your first name:");
if(firstName != "" && firstName != null) {
// Set cookie using our custom function
setCookie("firstName", firstName, 30);
}
}
}

Updating a Cookie
The only way to update or modify a cookie is to create another cookie with the
same name and path as an existing one. Creating a cookie with the same name but with a
different path then that of an existing one will add an additional cookie. Here's an example:

Example
Try this code »
// Creating a cookie
document.cookie = "firstName=Christopher; path=/; max-age=" + 30*24*60*60;

// Updating the cookie


document.cookie = "firstName=Alexander; path=/; max-age=" + 365*24*60*60;

Deleting a Cookie
To delete a cookie, just set it once again using the same name, specifying an empty or arbitrary
value, and setting its max-age attribute to 0. Remember that if you've specified a path,
and domain attribute for the cookie, you'll also need to include them when deleting it.
Example
Try this code »
// Deleting a cookie
document.cookie = "firstName=; max-age=0";

// Specifying path and domain while deleting cookie


document.cookie = "firstName=; path=/; domain=example.com; max-age=0";
However, to delete a cookie using the expires attribute, simply set its value (i.e. the expiration
date) to a date that has already passed, as demonstrated below.
document.cookie = "firstName=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";

You might also like