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

What is ES6?

ES6 is an acronym of ECMAScript 6 and also known as ECMAScript 2015.

ES6 or ECMAScript6 is a scripting language specification which is standardized by ECMAScript


International. It is used by the applications to enable client-side scripting. This specification is affected
by programming languages like Self, Perl, Python, Java, etc. This specification governs some languages
such as JavaScript, ActionScript, and Jscript. ECMAScript is generally used for client-side scripting, and
it is also used for writing server applications and services by using Node.js.

ES6 allows you to make the code more modern and readable. By using ES6 features, we write less and
do more, so the term 'Write less, do more' suits ES6. ES6 introduces you many great features such as
scope variable, arrow functions, template strings, class destructions, modules, etc.

ES6 was created to standardize JavaScript to help several independent implementations. Since the
standard was first published, JavaScript has remained the well-known implementation of ECMAScript,
comparison to other most famous implementations such as Jscript and ActionScript.

History
The ECMAScript specification is the standardized specification of scripting language, which is developed
by Brendan Eich (He is an American technologist and the creator of JavaScript programming
language) of Netscape (It is a name of brand which is associated with Netscape web browser's
development).

Initially, the ECMAScript was named Mocha, later LiveScript, and finally, JavaScript. In December
1995, Sun Microsystems (an American company that sold the computers and its components,
software, and IT services. It created Java, NFS, ZFS, SPARC, etc.) and Netscape announced the
JavaScript during a press release.

During November 1996, Netscape announced a meeting of the ECMA International standard
organization to enhance the standardization of JavaScript.

ECMA General Assembly adopted the first edition of ECMA-262 in June 1997. Since then, there are
several editions of the language standard have published. The Name 'ECMAScript' was a settlement
between the organizations which included the standardizing of the language, especially Netscape and
Microsoft, whose disputes dominated the primary standard sessions. Brendan Eich commented that
'ECMAScript was always an unwanted trade name which sounds like a skin disease (eczema).'

Both JavaScript and Jscript aims to be compatible with the ECMAScript, and they also provide some of
the additional features that are not described in ECMA specification.

Line Breaks and Whitespaces


ECMAScript ignores the tabs, spaces, and the newlines that appear in the programs. We can use the
tabs, spaces, and newlines easily in the program and free to format and indent the program in a
reliable manner, which increases the readability of the code and makes it easy to understand.

There are some important points in the reference of JavaScript that are defined as follows:
JavaScript and Camel Case
JavaScript programmers should use the Lower Camel Case (starts with a lowercase letter).

e.g. userName, firstName, cityName, etc.

It is to be noted that hyphens are not allowed in JavaScript, because hyphens are reserved for
subtractions.

JavaScript is Case-Sensitive
The identifiers in JavaScript are case-sensitive. It means that uppercase characters and lowercase
characters are different in JavaScript.

For example:

username and userName both are the different variables in JavaScript

1. var username, userName;


2. username = "Anil";
3. userName = "Sunil";

Semicolons are optional


The use of semicolons is optional in JavaScript. But if a single line has multiple statements (sequence
of instructions) then, these statements must be separated by the semicolons.

For example:

1. console.log("hello world")
2. console.log("Welcome to javaTpoint.com"); console.log("You are learning the ES6 tutorial");

Execution of Code in JavaScript

Let us try to understand how code executes in JavaScript by using an example:

1. var msg = "Hello World" //This line declares a variable.


2. console.log(msg); //This line print the value of the variable to the prompt. The console in it refers t
o the terminal window, and the log() is used to display the text on the screen.

Save this file by using .js extension as we are saving it with name Example.js. Then, right-click on
this file, which is placed under the working files option in the project explorer window of the visual
studio code, and select the 'open in terminal' option.

Type the following command in a terminal for executing the file:

1. node Example.js

After the successful execution, you will get the following output:
1. Hello World

The Strict Mode


The strict mode was introduced in ECMAScript 5 (the fifth edition of the ECMAScript specification). You
can use this strict mode in all of your programs. It will help you to write clean code, like preventing you
from using undeclared variables.

Advantages of using strict mode:


There are several changes that strict mode makes to normal JavaScript semantics:

o The strict mode prohibits some of the syntaxes, which is likely to be defined within the future
versions of ECMAScript.
o Strict mode removes some of the JavaScript silent errors by changing them to throw errors.
o The strict mode also fixes the mistakes, which makes it difficult for the JavaScript engines to
perform optimizations, so the strict mode sometimes makes to run faster compared to the
identical mode.

How to declare the strict mode


You can declare the strict mode by adding "use strict"; at the beginning of a function or a script.

Declare at the beginning of the script:When you declare it at the beginning of the script then, it will
be a global scope, i.e., all code within the script will execute in the strict mode.

For example:

1. "use strict";
2. example();
3. function example() {
4. x= 89; // It will also cause an error because x is not declared<br>
5. }

When we execute this example, we will get an error because we have not declared the variable x.

Declare inside the function: When you declare it inside the function, then it will be a local scope,
i.e., the code within the function will be in strict mode.

1. y = 89; // It will not cause an error.


2. example();
3. function example() {
4. "use strict";
5. x = 89; // It will cause an error
6. }

ES6 and Hoisting


Hoisting is the default behavior to move all of the declarations at the top of the scope before the
execution of code. It applies to functions and variables. It allows the JavaScript to use the component
before its declaration. Hoisting does not apply to scripts that run in strict mode.

ES6 Spread Operator


ES6 introduced a new operator referred to as a spread operator, which consists of three dots (...). It
allows an iterable to expand in places where more than zero arguments are expected. It gives us the
privilege to obtain the parameters from an array.

Spread operator syntax is similar to the rest parameter, but it is entirely opposite of it. Let's
understand the syntax of the spread operator.

Syntax
1. var variablename1 = [...value];

The three dots (...) in the above syntax are the spread operator, which targets the entire values in the
particular variable.

Let us try to understand the usage of spread operator in different cases:

Spread Operator and Array Manipulation


Here, we are going to see how we can manipulate an array by using the spread operator.

Constructing array literal


When we construct an array using the literal form, the spread operator allows us to insert another
array within an initialized array.

Example

1. let colors = ['Red', 'Yellow'];


2. let newColors = [...colors, 'Violet', 'Orange', 'Green'];
3. console.log(newColors);

Output

[ 'Red', 'Yellow', 'Violet', 'Orange', 'Green' ]

Concatenating arrays
Spread operator can also be used to concatenate two or more arrays.

Example

1. let colors = ['Red', 'Yellow'];


2. let newColors = [...colors, 'Violet', 'Orange', 'Green'];
3. console.log(newColors);

Output
[ 'Red', 'Yellow', 'Violet', 'Orange', 'Green' ]

Copying an array
We can also copy the instance of an array by using the spread operator.

Example

1. let colors = ['Red', 'Yellow'];


2. let newColors = [...colors];
3. console.log(newColors);

Output

[ 'Red', 'Yellow' ]

If we copy the array elements without using the spread operator, then inserting a new element to the
copied array will affect the original array.

But if we are copying the array by using the spread operator, then inserting an element in the copied
array will not affect the original array.

Let's understand the illustration for the same.

Example

Without using spread operator

1. let colors = ['Red', 'Yellow'];


2. let newColors = colors;
3. newColors.push('Green');
4. console.log(newColors);
5. console.log(colors);

Output

[ 'Red', 'Yellow', 'Green' ]


[ 'Red', 'Yellow', 'Green' ]

Using spread operator

1. let colors = ['Red', 'Yellow'];


2. let newColors = [...colors];
3. newColors.push('Green');
4. console.log(newColors);
5. console.log(colors);

Output

[ 'Red', 'Yellow', 'Green' ]


[ 'Red', 'Yellow' ]
Note: Instead of elements, the spread operator only copies the array itself to the new one. It means
that the operator can do a shallow copy instead of a deep copy.

Spread operator and Strings


Let's see how the spread operator spreads the strings. The illustration for the same is given below.

Example

Here, we have constructed an array str from individual strings.

1. let str = ['A', ...'EIO', 'U'];


2. console.log(str);

In the above example, we have applied the spread operator to the string 'EIO'. It spreads out each
specific character of the 'EIO' string into individual characters.

We will get the following output after the execution of the above code.

Output

[ 'A', 'E', 'I', 'O', 'U' ]

ES6 Rest Parameter


The rest parameter is introduced in ECMAScript 2015 or ES6, which improves the ability to handle
parameters. The rest parameter allows us to represent an indefinite number of arguments as an array.
By using the rest parameter, a function can be called with any number of arguments.

Before ES6, the arguments object of the function was used. The arguments object is not an instance
of the Array type. Therefore, we can't use the filter() method directly.

The rest parameter is prefixed with three dots (...). Although the syntax of the rest parameter is
similar to the spread operator, it is entirely opposite from the spread operator. The rest parameter has
to be the last argument because it is used to collect all of the remaining elements into an array.

Syntax
1. function fun(a, b, ...theArgs) {
2. // statements
3. }

Example
1. function show(...args) {
2. let sum = 0;
3. for (let i of args) {
4. sum += i;
5. }
6. console.log("Sum = "+sum);
7. }
8.
9. show(10, 20, 30);

Output

Sum = 60

All the arguments that we have passed in the function will map to the parameter list. As stated above,
the rest parameter (...) should always be at last in the list of arguments. If we place it anywhere else,
it will cause an error.

The rest parameter with the following syntax will cause an error.

1. function show(a,...rest, b) {
2. // error
3. };

Difference between Rest Parameter and arguments object


The rest parameter and arguments object are different from each other. Let's see the difference
between the rest parameter and the arguments object:

o The arguments object is an array-like (but not array), while the rest parameters are array
instances. The arguments object does not include methods such as sort, map,
forEach, or pop, but these methods can be directly used in rest parameters.

Rest Parameters and Destructuring


Destructuring means to break down a complex structure into simpler parts. We can define an array as
the rest parameter. The passed-in arguments will be broken down into the array. Rest parameter
supports array destructuring only.

By using the rest parameter, we can put all the remaining elements of an array in a new array.

Let's see an illustration of the same.

Example
1. var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];
2.
3. // destructuring assignment
4. var [a,b,...args] = colors;
5. console.log(a);
6. console.log(b);
7. console.log(args);

Output

Violet
Indigo
[ 'Blue', 'Green', 'Yellow', 'Orange', 'Red' ]
Rest Parameter in a dynamic function
JavaScript allows us to create dynamic functions by using the function constructor. We can use the
rest parameter within a dynamic function.

Example
1. let num = new Function('...args','return args');
2. console.log(num(10, 20, 30));

Output

[ 10, 20, 30 ]

ES6 Variables
A variable is a named space in the memory, which stores the values. The names of the variable are
known as identifiers. There are some rules that you should keep in mind while naming an identifier.
These rules are as follows:

o It can contain numbers and alphabets.


o You cannot start the name of the variable with a number.
o Keywords cannot be used as the name of the variable.
o Identifiers do not contain spaces and special characters except the dollar ($)
symbol and underscore (_).

Initialization of Variable
It is the process to store the value in the variable. A variable can be initialized at any time before its
use.

The ES6 syntax used the keyword var to declare a variable. In ES5, we declare the variable like this:

1. var x //Declaration of a variable by using the var keyword

Valid type of syntax for variable declaration


Some variable declarations are considered to be valid are as follows:

1. var $example1=value
2. var example1=value
3. var _example$=value

In ES6, the variables are declared by:

o Using let.
o Using const.

let:
Any variable which is declared by using the let keyword is assigned the block scope. Block scope is
nothing but a section where the let variable gets declared whether it is a function{}, a block{}, or
a global (script).

For example: var v/s let

By using var

1. var x = 100;
2. var x=200;
3. console.log(x);

When the code gets successfully executed, you will get the following output:

Output:

200

Let us try to re-write the above code by using the let keyword:

By using let

1. let x = 100;
2. let x=200;
3. console.log(x);

Output:

SyntaxError: Identifier 'x' has already been declared

When the code gets successfully executed, you will get an error that the identifier 'x' has already been
declared. So, any variable which is declared by using the let keyword is assigned the block scope.

const:
ES6 gives a new way to declare a constant using the const keyword. The keyword const creates a
read-only reference to the value. There are some properties of the const that are as follows:

Properties:

o It cannot be reassigned a value.


o It is block scoped.
o A constant cannot be re-declared.
o Constants must be initialized at the time of declaration.

For example:

1. const y=100
2. y=200 // It will result in an error

Output:

TypeError: Assignment to constant variable.


It will throw an error because the constant variables are immutable and cannot be reassigned a value.

JavaScript Variable Scope


There are two scopes in JavaScript that are global and local:

o Global Scope: In the global scope, the variable can be accessed from any part of the
JavaScript code.
o Local Scope: In the local scope, the variable can be accessed within a function where it is
declared.

Example:

The following example describes the Global and Local scope:

In this example, there are two variables one is outside the function (global scope), and the other is in
the function (local scope).

1. var $var12 = 200;


2.
3. function example() {
4. var $var12 = 300;
5. console.log("Inside example() function = "
6. + $var12);
7. }
8. console.log("Outside example() function = "
9. + $var12);
10. example();

Output:

Outside example() function = 200


Inside example() function = 300

JavaScript Dynamic Typing


JavaScript supports the concept of Dynamic Typing as similar to python, perl, ruby, etc. It is a
feature where you do not need to tell JavaScript about what type of value the variable will hold. If the
type of value of the variable gets changed during the execution of the program, then it gets triggered,
and JavaScript automatically takes care of it.

ES6 and Variable Hoisting


Hoisting is the default behavior of JavaScript to move all declarations to the top of the current script,
current function, or current scope. It allows you to use the variable before its declaration. JavaScript
only hoists the variable declaration, not variable initialization.

For example:

JavaScript Declarations are Hoisted

1. x=10;
2. console.log(x);
3. var x;

Instead of giving a declaration error, the above code will successfully execute and show the desired
output. It happens because of the hoisting concept. Let us see what happens when the code is in the
compiling phase.

When the above code is in the compile phase, then it will be treated as:

In Compile phase

1. var x; // declaration of the variable will move on top.


2. x=10;
3. console.log(x);

Output:

10

JavaScript Initializations are not Hoisted


1. When you initialize the variable before using it

1. var x=100;
2. var y=200;
3. console.log(x+" "+y);

In compiling phase

1. var x;
2. var y;
3. x=100;
4. y=200;
5. console.log(x+" "+y);

Output:

100 200

II. When you initialize the variable after using it

1. var x=100;
2. console.log(x+" "+y);
3. var y=200;

Let us see what happens when this code is in the compile phase.

When this code is in compiling, then it will be treated as follows:

In Compiling phase

1. var x;
2. var y;
3. x=100;
4. console.log(x+" "+y);
5. y=200;

When you execute this code, you will get the following output in which the value of y is undefined.

Output:

100 undefined

This happens because hoisting does not allow us to move the initialization of variables on the top if you
initialize them after using.

Bitwise Operators
Bitwise operators are used for performing the bitwise operations on binary numerals or bit patterns
that involve the manipulation of individual bits. Bitwise operators perform the operation on the binary
representation of arguments

Generally, bitwise operators are less used and relevant for the applications and hyper-performance
programs.

ES6 Loops
Looping statements in the programming languages help to execute the set of instructions/functions
repeatedly while a condition evaluates to true. Loops are an ideal way to perform the execution of
certain conditions repeatedly. In a loop, the repetition is termed as iteration.

You can see the classification of loops in the following figure:

Let us try to understand the loops in the above image.

Definite Loops
A definite loop has a definite/fixed number of iterations. In ES6, there are three types of definite loops
that are listed below:
Definite Loop Description

for( ; ; ) Loop It executes the block of code for a definite number of times.

for…in Loop It iterates through the properties of the object.

for…of loop Unlike object literals, it iterates the iterables (arrays, string, etc.).

Let us try to elaborate on the above loops.

The for ( ; ; ) loop


The for ( ; ; ) loop is used to iterate a part of the program multiple times. If you have a fixed number
of iterations, then it is always recommended to use 'for' loop.

Syntax

1. for(initialization;condition;incr/decr){
2. //statement or code to be executed
3. }

The 'for' loop includes some parts that are defined as follows:

o Initialization: It is the initial condition that is executed once at the starting of the loop. In this
part, we initialize the variable, or it can also be used for the already initialized variable. It is an
optional statement.
o Condition: It is executed each time for testing the condition of the loop. It continues the
execution of the loop until the condition is false. It returns only Boolean values that are either
true or false. It is also an optional statement.
o Increment/Decrement: It can increment or decrement the value of the variable, and it is also
an optional statement.
o Statement: It represents the body of the loop, which is executed every time until the
conditional expression is false.

Flowchart
Example

In the following, there are three examples of 'for' loop in which we are showing the simple 'for' loop,
'for' loop having multiple expressions and infinite 'for' loop.

o The table of 2 by using for loop.

1. var i;
2. for(i=1;i<=10;i++)
3. {
4. console.log("2 x "+ i +" =", 2*i);
5. }

Output

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
o for loop having multiple expressions
You can combine the multiple assignments and final expressions in a single for loop by using
the comma (, ) operator.
Let us try to print the Fibonacci series by using the single for loop.
1. "use strict"
2. for(let temp, a = 0, b = 1; b<40; temp = a, a = b, b = a + temp)
3. console.log(b);

Output

1
1
2
3
5
8
13
21
34
o Infinite for loop
The example of infinite for loop is given as follows:

1. for(;;)
2. {
3. console.log("infinitive loop"); // It will print infinite times
4. }

Output

infinite loop
infinite loop
infinite loop
infinite loop
infinite loop
infinite loop
infinite loop
infinite loop
infinite loop
infinite loop
infinite loop
infinite loop
.
.
.
.
infinite loop

For terminating it, you can use ctrl + c.

The for…in loop


The for…in loop is similar to for loop, which iterates through the properties of an object, i.e., when
you require to visit the properties or keys of the object, then you can use for…in loop. It is a better
choice when you are working with objects or dictionaries where the order of index is not essential.

Syntax

1. for (variable_name in object_name) //Here in is the keyword


2. {
3. // statement or block to execute
4. }
In every iteration, one property from the object is assigned to the name of the variable, and this loop
continues till all of the object properties get covered.

Example

1. function Mobile(model_no){
2. this.Model = model_no;
3. this.Color = 'White';
4. this.RAM = '4GB';
5. }
6. var Samsung = new Mobile("Galaxy");
7. for(var props in Samsung)
8. {
9. console.log(props+ " : " +Samsung[props]);
10. }

Output

Model : Galaxy
Color : White
RAM : 4GB

If you pass the function in the properties of the object then this loop will give you the complete
function in the output. You can it's illustration in the following code:

1. function Mobile(model_no){
2. this.Model = model_no;
3. this.Color = 'White';
4. this.RAM = '4GB';
5. this.Price = function price() // The loop will give you this function as it is written here.
6. {
7. console.log(this.model + "Price = Rs. 3300");
8. }
9. }
10. var Samsung = new Mobile("Galaxy");
11. for(var props in Samsung)
12. {
13. console.log(props+ " : " +Samsung[props]);
14. }

Output

Model : Galaxy
Color : White
RAM : 4GB
Price : function price()
{
console.log(this.model + "Price = Rs. 3300");
}

So, you can also visit the methods by using the for…in loop.
The for…of loop
Unlike the object literals, this loop is used to iterate the iterables (arrays, string, etc.).

Syntax

1. for(variable_name of object_name) // Here of is a keyword


2. {
3. //statement or block to execute
4. }

In every iteration, one property from the iterables gets assigned to the variable_name, and the loop
continues till the end of the iteration.

Example

1. var fruits = ['Apple', 'Banana', 'Mango', 'Orange'];


2. for(let value of fruits)
3. {
4. console.log(value);
5. }
6.
7. /*
8. You can also write the above code like:
9.
10. for(let value of ['Apple', 'Banana', 'Mango', 'Orange'])
11. {
12. console.log(value);
13. }
14.
15. */

Output

Apple
Banana
Mango
Orange

Indefinite Loops
An indefinite loop has infinite iterations. It is used when the number of iterations within the loop is
intermediate or unknown.

There are two types of indefinite loops that are listed below:

Indefinite Description
Loops
while Loop It executes the instructions each time till the defined condition evaluates to true.

do…while It is similar to the while loop, but the key difference is that the do…while loop execu
Loop once irrespective of the terminator condition.

Let us try to elaborate on the above loops.

The while loop


A while loop is a control flow statement that allows the repeated execution of code based on the given
Boolean condition. It consists of a block of code and an expression/condition.

The while loop checks the expression/condition before the execution of block; that's why this control
structure is often known as a pre-test loop.

Syntax

1. while (condition) {
2. statements;
3. }

Flowchart

Example

1. var y = 0;
2. while (y < 4) {
3. console.log(y);
4. y++;
5. }

Output

0
1
2
3
Points to remember

o The condition is always required in the while loop because it is necessary to run the loop. If the
condition returns true, then the loop will start over again, but if it returns false, the loop will
stop.
o If the condition will always true, then the loop will never end.

The do…while loop


It is a control flow statement that executes a block of code at least once, and then it will depend upon
the condition whether or not the loop executes the block repeatedly.

The do…while loop checks the condition after the execution of the block, that's why this control
structure is also known as the post-test loop. It is also possible that the condition always evaluates to
true, which will create an infinite loop.

Syntax

1. do
2. {
3. // block of statements to be executed;
4. }
5. while (expression);

Flowchart

Example

1. var count = 6, fact = 1;


2. do {
3. fact = fact * count--;
4. } while (count > 0);
5.
6. console.log(fact);
Output

720

If you perform this example by using the while loop, then this will be written as:

1. var count = 6, fact = 1;


2. while (count > 0)
3. {
4. fact = fact * count--;
5. }
6. console.log(fact);

Output

720

The key difference between the above two examples is that the while loop is entered only if the
condition passed to it will evaluate to true. But the do…while loop executes the statement once, it
happens because of the starting iteration of the do…while loop does not consider as the Boolean
expression. Then for the further iterations, the while will check the condition and takes the control out
from the loop.

The Loop control statements


The loop control statements are used for interrupting or control the flow of the execution. These
statements change the execution from its normal sequence. JavaScript provides you the full control to
handle the loops and switch statements.

There may be some circumstances when you require to come out from the loop without reaching its
bottom. There may also be some situations when you need to skip the part of the code and start the
further iterations of the loop. So, for handling such situations in JavaScript, we have a
break and continue statements.

Loop control Description


statements

The break The break statement is used to bring the control of the program out from th
statement

The continue It skips the subsequent statements of the current iteration and brings contro
statement to the beginning of the loop.

Let us try to elaborate on the above control statements.

The break statement


It is used to take control of the program out from the loop. You can use the break statements within
the loops or in the switch statements. Using a break statement within the loop causes the program to
exit from the loop.
Syntax

1. break;

Example

1. var n = 1;
2. while(n<=7)
3. {
4. console.log("n="+n);
5. if(n==4)
6. {
7. break;
8. }
9. n++;
10. }

The above code will print the four values of n for the range of numbers within 1 to 7.

When the value of n is 4, then the loop forces the control to exit the loop because of the break
statement. You will get the following output after the successful execution of the above code.

Output

n=1
n=2
n=3
n=4

The continue statement


Unlike the break statement, the continue statement does not exit from the loop. It terminates the
current iteration of the loop and starts the next iteration.

Syntax

1. continue;

Example

1. var n = 0;
2. while(n<=5)
3. {
4. n++;
5. if(n==3)
6. {
7. continue;
8. }
9. console.log("n = "+n);
10. }
The above example will display the values of n, but it will skip the current iteration if the value of n will
be 3. You will get the following output after the successful execution of the above code.

Output

n = 1
n = 2
n = 4
n = 5
n = 6

Use of Labels for controlling the flow


A label is nothing but an identifier followed by a colon (:), and it applied on a block of code or a
statement. You can use the label with a break and continue to control the flow.

You cannot use the line breaks in between the break and continue statement and its label name. Also,
there should not be any statement in between the label name and an associated loop.

The syntax for defining the label

1. labelname:
2. Statement

labelname: Any identifier of JavaScript, which is not a reserved word.

Statement: It is a JavaScript statement.

Note: In strict mode, you cannot use "let" as the label name. It will cause a syntax error because let is a
reserved identifier.

Label Description

Label with the break It is used to exit from the loop or from the switch statement without using
statement but with label reference, it is used to jump out from any code block.

Label with continue It is used to skip one iteration of the loop with or without using the label re
statement

Label with the break statement


Without using the label reference, you can use the break only to exit from the loop or from the switch,
but by using the label reference, you can use the break to jump out from any code block.

Syntax

1. break labelname;
Example

1. var x, y;
2.
3. loop1: //The first for statement is labeled as "loop1."
4.
5. for (x = 1; x < 4; x++) {
6. loop2: //The second for statement is labelled as "loop2"
7. for (y = 1; y < 4; y++) {
8. if (x === 2 && y === 2) {
9. break loop1;
10. }
11. console.log('x = ' + x + ', y = ' + y);
12. }
13. }

Output

x = 1, y = 1
x = 1, y = 2
x = 1, y = 3
x = 2, y = 1

Label with continue statement


The continue statement can only be used for skipping one loop iteration either with the label reference
or without using the label reference.

Syntax

1. continue labelname;

Example

1. var x, y;
2.
3. loop1: //The first for statement is labelled as "loop1"
4. for (x = 1; x < 4; x++) {
5. loop2: //The second for statement is labelled as "loop2"
6. for (y = 1; y < 4; y++) {
7. if (x === 2 && y === 2) {
8. continue loop1;
9. }
10. console.log('x = ' + x + ', y = ' + y);
11. }
12. }

You can notice in the following output of the above code that it skips both "x = 2, y = 2" and "x = 2, y
= 3".

Output
x = 1, y = 1
x = 1, y = 2
x = 1, y = 3
x = 2, y = 1
x = 3, y = 1
x = 3, y = 2
x = 3, y = 3

Labeled function declarations


Before ECMAScript 6, the LabeledStatement specification didn't allow for the association of a label
statement with a FunctionDeclaration. However, the labeled FunctionDeclaration was the
allowable extension in non-strict code, and most of the browser-hosted implementations of
ECMAScript supported that extension.

But in ECMAScript 2015 (ES6), the grammar productions for the LabeledStatement allow the use
of FunctionDeclaration as a LabeledItem, but it includes an error rule that causes a syntax error if
that occurs.

For the web browser compatibility, that rule is modified with the addition of underlined text:

LabeledItem : FunctionDeclaration

It will cause a syntax error if any of the source code of strict mode matches this rule.

Starting with ECMAScript 2015, the labelled function declarations standardized for non-strict code:

1. L: function hello() {}

If you write the above code in strict mode then this will throw a syntax error:

1. 'use strict';
2. L: function hello() {}
3. // SyntaxError: In strict mode code, functions can only be declared at top level or inside a block.

The Generator Functions can neither be labeled in non-strict mode nor in strict mode.

1. L: function* hello()
2. {
3. }
4. // SyntaxError: Generator Functions cannot be labelled

The switch statement


It is a multi-way branch statement that is also used for decision-making purposes. In some cases,
the switch statement is more convenient than if-else statements. It is mainly used when all
branches depend upon the value of a single variable. It executes a block of code depending upon the
different cases.

The switch statement uses the break or default keywords, but both of them are optional. Let us
define these two keywords:

break: It is used within the switch statement for terminating the sequence of a statement. It is
optional to use. If it gets omitted, then the execution will continue on each statement. When it is used,
then it will stop the execution within the block.
default: It specifies some code to run when there is no case match. There can be only a single default
keyword in a switch. It is also optional, but it is recommended to use it as it takes care of unexpected
cases.

If the condition passed to switch doesn't match with any value in cases, then the statement under the
default will get executed.

Some points to remember

o There can be one or multiple case values for a switch expression.


o The use of break and default keywords are optional.
o The case statements can only include constants and literals. It cannot be an expression or a
variable.
o Unless you put a break after the code of every block, the execution will continuously flow into
the next block.
o It is not necessary that the default case has to be placed at last in a switch block.

Syntax

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

Flowchart
ES6 Generators
Generator (or Generator function) is the new concept introduced in ES6. It provides you a new way of
working with iterators and functions.

ES6 generator is a different kind of function that may be paused in the middle either one or many
times and can be resumed later. When the standard function is called, the control rests with the called
function until it returns, but the generator in ES6 allows the caller function to control the execution of a
called function.

A generator is somewhere identical to the regular function except that:

o When the generator gets called, it doesn't run its code. Instead, it returns a special object which
is called as 'Generator Object' for managing the execution.
o The generator function can return (or yield) the control back to the caller at any point.
o Unlike the regular function, the generator can return (or yield) the multiple values, one after
another, on the requirement.

Syntax
The syntax of the generator function is almost identical to regular function. The only real difference is
that the generator function is denoted by suffixing the function keyword with an asterisk (*).

In the following syntax, we are showing you some of the valid ways of defining the generator function:
1. function* mygenfun() // Valid
2. {
3. yield 1;
4. yield 2;
5. ...
6. ...
7. }
8.
9. function *mygenfun() // Valid
10. {
11. yield 1;
12. yield 2;
13. ...
14. ...
15. }
16.
17. function*mygenfun() // Valid
18. {
19. yield 1;
20. yield 2;
21. ...
22. ...
23. }

Example
1. function* gen()
2. {
3. yield 100;
4. yield;
5. yield 200;
6. }
7. // Calling the Generator Function
8. var mygen = gen();
9. console.log(mygen.next().value);
10. console.log(mygen.next().value);
11. console.log(mygen.next().value);

Output

100
undefined
200

The yield statement


The yield statement suspends the function execution and sends a value back to the caller. It retains
enough state to enable function to resume where it is left off. When it gets resumed, the function
continues the execution immediately after the last yield run. It can produce a sequence of values.
next() method
In the above example, we have used the next() method, which is the main method of the generator.
When you call the next() method along with an argument, it will resume the execution of the
generator function, replacing the yielded expression where the execution was paused with the
argument from the next() method.

The result of the next() method is always an object having two properties:

o value: It is the yielded value.


o done: It is a Boolean value which gives true if the function code has finished. Otherwise, it
gives false.

For instance, here, we are creating a generator function and gets its yielded value.

Example
1. function* show() {
2. yield 100;
3. }
4.
5. var gen = show(); //here 'gen' is a generator object
6. console.log(gen.next()); // { value: 100, done: false }

Output

{ value: 100, done: false }

Generator object
The generator functions return generator objects. A generator object is an instance of the generator
function, and it conforms to both the iterable and iterator interfaces.

The generator objects can be used either by calling the next() method or by using the generator
object within a loop. The generator object is an iterator; that's why you can use it in for…of loops or in
other functions accepting an iterable.

In the above next() method example, the variable gen is the generator object.

Return Statement in a Generator


Return is used to send a specified value back to its caller. It is used to end the function call execution
and returns the result to the caller. Within a function, the statements defined after the return
statements are not executed. That's why the return statement should be the last statement of the
function.

Let us try to understand the return statement in a generator by using an example:

Example
1. function* myGen() {
2. yield 'First yield statement';
3. yield 'Second yield statement';
4. return 'Return statement';
5. yield 'Second yield statement';
6. }
7. let genobj = myGen();
8.
9. console.log(genobj.next()); //returns {value: 'First yield statement', done: false}
10.
11. console.log(genobj.next()); //returns {value: 'Second yield statement', done: false}
12.
13. console.log(genobj.next()); //returns {value: 'Return statement', done: true}
14.
15. console.log(genobj.next()); //returns {value: undefined, done: true}

Output

{ value: 'First yield statement', done: false }


{ value: 'Second yield statement', done: false }
{ value: 'Return statement', done: true }
{ value: undefined, done: true }

In the above example, we have defined a generator function myGen() in which we have defined four
statements, including three yield statements and a return statement. Whenever we call the next()
method, the function resumes until it hits the next yield statement.

You can notice how the first next() method returns 'First yield statement .' When we call
the next() method a second time, it resumes the execution and returns 'Second yield statement'.
After calling the next() method again, the function finds no more yield statement and returns
the 'Return statement.' But when we call the next() method fourth time, it will not consider
the yield statement and returns undefined because it is written after the return statement.

You can see in the output of the above example that the next() method is not considering any
statement after the return statement.

Generator function with for…of loop


Using for…of loop with generator function reduces the line of code. You can see the illustration for the
same in the following example.

1. "use strict"
2. function* vowels() {
3. // here the asterisk marks this as a generator
4. yield 'A';
5. yield 'E';
6. yield 'I';
7. yield 'O';
8. yield 'U';
9. }
10. for(let alpha of vowels()) {
11. console.log(alpha);
12. }
Output

A
E
I
O
U

Note: Generator functions cannot be represented by using the arrow functions.

Anonymous function
An anonymous function can be defined as a function without a name. The anonymous function does not
bind with an identifier. It can be declared dynamically at runtime. The anonymous function is not
accessible after its initial creation.

An anonymous function can be assigned within a variable. Such expression is referred to as function
expression. The syntax for the anonymous function is as follows.

Syntax

1. var y = function( [arguments] )


2. {
3. //code to be executed
4. }

Example

1. var hello = function() {


2. console.log('HelloWorld');
3. console.log('I am an anonymous function');
4. }
5. hello();

Output

Hello World
I am an anonymous function

Anonymous function as an argument


One common use of the anonymous function is that it can be used as an argument to other functions.

Example

Use as an argument to other function.

1. setTimeout(function()
2. {
3. console.log('Hello World');
4. }, 2000);
When you execute the above code, it will show you the output after two seconds.

Output

Hello World

Parameterized Anonymous function


Example

1. var anon = function(a,b)


2. {
3. return a+b
4. }
5. function sum() {
6. var res;
7. res = anon(100,200);
8. console.log("Sum: "+res)
9. }
10. sum()

Output

Sum: 300

ES6 Arrow Function


Arrow functions are introduced in ES6, which provides you a more accurate way to write the functions
in JavaScript. They allow us to write smaller function syntax. Arrow functions make your code more
readable and structured.

Arrow functions are anonymous functions (the functions without a name and not bound with an
identifier). They don't return any value and can declare without the function keyword. Arrow functions
cannot be used as the constructors. The context within the arrow functions is lexically or statically
defined. They are also called as Lambda Functions in different languages.

Arrow functions do not include any prototype property, and they cannot be used with the new keyword.

Syntax for defining the arrow function

1. const functionName = (arg1, arg2, ?..) => {


2. //body of the function
3. }

There are three parts to an Arrow Function or Lambda Function:

o Parameters: Any function may optionally have the parameters.


o Fat arrow notation/lambda notation: It is the notation for the arrow (=>).
o Statements: It represents the instruction set of the function.

Let us try to understand it with an example.


In the following example, we are defining three functions that show Function Expression,
Anonymous Function, and Arrow Function.

1. // function expression
2.
3. var myfun1 = function show() {
4. console.log("It is a Function Expression");
5. }
6.
7. // Anonymous function
8.
9. var myfun2 = function () {
10. console.log("It is an Anonymous Function");
11. }
12.
13. //Arrow function
14.
15. var myfun3 = () => {
16. console.log("It is an Arrow Function");
17. };
18.
19. myfun1();
20. myfun2();
21. myfun3();

Output

It is a Function Expression
It is an Anonymous Function
It is an Arrow Function

Syntactic Variations
There are some syntactic variations for the arrow functions that are as follows:

o Optional parentheses for the single parameter

1. var num = x => {


2. console.log(x);
3. }
4. num(140);

Output

140
o Optional braces for single statement and the empty braces if there is not any
parameter required.

1. var show = () => console.log("Hello World");


2. show();
Output

Hello World

Arrow Function with Parameters


If you require to pass more than one parameter by using an arrow function, then you have to pass
them within the parentheses.

For example

1. var show = (a,b,c) => {


2. console.log(a + " " + b + " " + c );
3. }
4. show(100,200,300);

Output

100 200 300

Arrow function with default parameters


In ES6, the function allows the initialization of parameters with default values, if there is no value
passed to it, or it is undefined. You can see the illustration for the same in the following code:

For example

var show = (a, b=200) => {


console.log(a + " " + b);
}
show(100);

In the above function, the value of b is set to 200 by default. The function will always consider 200 as
the value of b if no value of b is explicitly passed.

Output

100 200

The default value of the parameter 'b' will get overwritten if the function passes its value explicitly. You
can see it in the following example:

For example

1. var show = (a, b=200) => {


2. console.log(a + " " + b);
3. }
4. show(100,500);

Output

100 500
Arrow function with Rest parameters
Rest parameters do not restrict you to pass the number of values in a function, but all the passed
values must be of the same type. We can also say that rest parameters act as the placeholders for
multiple arguments of the same type.

For declaring the rest parameter, the parameter name should be prefixed with the spread operator that
has three periods (not more than three or not less than three).

You can see the illustration for the same in the following example:

1. var show = (a, ...args) => {


2. console.log(a + " " + args);
3. }
4. show(100,200,300,400,500,600,700,800);

Output

100 200,300,400,500,600,700,800

Arrow Function without Parentheses


If you have a single parameter to pass, then the parentheses are optional.

For example

1. var show = x => {


2. console.log(x);
3. }
4. show("Hello World");

Output

Hello World

Advantages of Arrow Functions


There are some advantages of using arrow functions that are shown in the below image:

Let us try to elaborate on the advantages which are available in the above image.

1. It reduces the code size: When we use the syntax of arrow function, the size of the code gets
reduced. We can write less amount of code by using the arrow function.

2. Return statement and Functional braces are optional for single line functions:In ES5, we
need to define the return statement in the functions, but in ES6, we do not require to define the return
statement for single-line functions. Functional braces are also optional for the single-line functions.

For example
In ES5

1. function show(value){
2. return value/2;
3. }

In ES6

1. var show = value => value/2;


2. console.log(show(100));

Note: If you are not applying curly braces on the single statement, then you do not require
to use return, but if you are using curly braces even on the single statement, then you must
have to use the return keyword.

You can understand it in the following example:

Without Return Keyword

1. var show = value => {


2. value/2;
3. }
4. console.log(show(50));

Output

undefined

With Return Keyword

1. var show = value => {


2. return value/2;
3. }
4. console.log(show(50));

Output

25

3. Lexically bind the context: Arrow function binds the context lexically or statically. The handling
of this is different in arrow functions as compared to regular functions. In the arrow function, there is
not any binding of this. In regular functions, this keyword is used to represent the objects that called
the function, which could either be a window, a button, or a document or anything.

But with arrow functions, this keyword always represents the object that defines the arrow function.

Let us try to understand it with the following piece of code:

For example

Consider a class having an array of numbers, and if the number is less than 30, then we will push them
into the child queue.

In ES5, it can be done as follows


1. this.num.forEach(function(num) {
2. if (num < 30)
3. this.child.push(num);
4. }.bind(this));

In ES6, it can be done by using the arrow function

1. this.num.forEach((num) => {
2. if (num < 30)
3. this.child.push(num);
4. });

So, by using the arrow function, we do not require to bind it implicitly because it performs
automatically by the arrow function.

As we have seen, the arrow function makes the writing of function less complicated, and it also reduces
the number of lines.

Function Hoisting
As variable hoisting, we can perform the hoisting in functions. Unlike the variable hoisting, when
function declarations get hoisted, it only hoists the function definition instead of just hoisting the name
of the function.

Let us try to illustrate the function hoisting in JavaScript by using the following example:

Example

In this example, we call the function before writing it. Let's see what happens when we call the function
before writing it.

1. hello();
2. function hello() {
3. console.log("Hello world ");
4. }

Output

Hello world

In the above code, we have called the function first before writing it, but the code still works.

However, function expressions cannot be hoisted. Let us try to see the illustration of hoisting the
function expressions in the following example.

1. hello();
2.
3. var hello = function() {
4. console.log("Hello world ");
5. }

When you execute the above code, you will get a "TypeError: hello is not a function." It happens
because function expressions cannot be hoisted.
Output

TypeError: hello is not a function

The Function Constructor


It is the way of defining a new function. The function statement is not the single way to define a new
function; we can also dynamically define the function by using the Function() constructor along with
the new operator.

It is less efficient than declaring a function using a function expression or function statement.

Syntax

The syntax of creating the function by using the Function() constructor.

1. var variable_name = new Function(arg1, arg2..., "Body of the Function");

Parameters used

Its syntax includes:

arg1, arg2, … argN: These are the names that are used by the function as the name of the formal
arguments. Each argument must be a string that corresponds to a valid identifier of JavaScript.

Function Body: It is a string that contains the statements of JavaScript comprises the function
definition.

It can include any number of string arguments. The last argument is the body of the function, which
can contain arbitrary statements of JavaScript, which is separated from each other by semicolons.

The function() constructor does not pass any argument that specifies a name for the function it
creates.

Example

1. // creating a function that takes two arguments and returns the product of both arguments
2. var mul = new Function('a', 'b', 'return a * b');
3.
4. // calling of function
5. console.log("The product of the numbers is: " +mul(5, 5));

Output

The product of the numbers is: 25

Immediately Invoked Function Expression (IIFE)


It is a function in JavaScript that runs as soon as it is defined. An IIFE (Immediately Invoked
Function Expression) can be used for avoiding the variable hoisting from within the blocks. It allows
the public access to methods while retaining the privacy for variables defined in the function.

You can learn more about the IIFEs by clicking on this link Immediately Invoked Function Expression
(IIFE)
JavaScript Functions and Recursion
When a function calls itself, then it is known as a recursive function. Recursion is a technique to
iterate over an operation by having a function call itself repeatedly until it reaches a result.

It is the best way when we require to call the same function regularly with different parameters in a
loop.

Example

1. function fact(num) {
2. if (num <= 1) {
3. return 1;
4. } else {
5. return num * fact(num - 1);
6. }
7. }
8. console.log(fact(6));
9. console.log(fact(5));
10. console.log(fact(4));

Output

720
120
24

Function Expression v/s Function Declaration


The fundamental difference between both of them is that the function declarations are parsed before
the execution, but the function expressions are parsed only when the script engine encounters it during
the execution.

Unlike the function declarations, function expressions in JavaScript do not hoists. You cannot use the
function expressions before defining them.

The main difference between a function declaration and function expression is the name of the
function, which can be omitted in the function expressions for creating the anonymous functions.

Immediately Invoked Function Expression (IIFE)


It is a JavaScript function that runs as soon as it defined. An IIFE (Immediately Invoked Function
Expression) can be used for avoiding the variable hoisting from within the blocks. It allows the public
access to methods while retaining the privacy for variables defined in the function.

IIFE is a design pattern that is also known as the Self-Executing Anonymous Function. It contains
two major parts:

o The first part is the anonymous function having a lexical scope, which is enclosed within
the Grouping operator ().
o The second part creates the IIFE by which the JavaScript engine will interpret the function
directly.
Syntax
1. (function ()
2. {
3. statements
4. })();
5.
6. // Syntax of IIFE with ES6 arrow functions (though parentheses only allowed on outside)
7.
8. (() => { /* ... */ })();

Let us try to understand the concept of IIFE by using the following example.

Example
1. (function()
2. {
3. console.log("Hello World");
4. })();

Output

Hello World

Conversion of Functions into IIFEs


We can convert the regular functions into IIFE by using the following steps:

o Suppose any regular function definition.


o Wrap that definition within the pair of parentheses, which will create the function expression.
o At last, we have to add a pair of parentheses and a semicolon for marking the end of the
statement.

Let's see the illustration for the same in the following example:

Example
1. // Regular Function.
2. function hello()
3. {
4. console.log("Regular function");
5. };
6. // Regular Function execution.
7. hello();
8.
9. // IIFE creation and execution.
10. (function() { console.log("Immediately Invoked Function Expression"); })();

Output
Regular function
Immediately Invoked Function Expression

Key points about IIFEs


o Immediately invoked function expressions (IIFEs) have their scope. The variables declared in
the function expression will not be available outside the function.
o Like other functions, IIFEs can also be anonymous or named.
o IIFEs can also be parameterized. For example,

Example
1. (function (x, y, z) {
2. console.log(x);
3. console.log(y);
4. console.log(z);
5. })(100, 200, 300);

Output

100
200
300

ES6 Arrays
Array in JavaScript is an object which is used to represent a collection of similar type of elements. It
allows you to store more than one value or a group of values in a single variable name. Arrays are
used for storing the collections of values in chronological order. An array is the collection of
homogeneous elements, or we can say that array is the collection of values of same data-type.

We can store any valid values such as objects, numbers, strings, functions, and also other arrays,
which make it possible to create complex data structures like an array of arrays or an array of objects.

Syntax
There are two ways of declaring an array.

1. var array_name = new Array(); // By using the new keyword


2.
3. var array_name = [value1, value2,....valueN]; //By using Array literals
4. or,
5. var array_name; //Declaration
6. array_name=[value1, value2,…..valueN]; //Initialization

The array parameter contains the list of integers and strings. It is recommended to use an array
literal for creating an array instead of using the new keyword.

The new keyword only complicates the code, and sometimes it produces unexpected results. If you
specify a single numeric parameter in the constructor of an array (or creating an array with the
new keyword), then it will be treated as the length of an array.
Note: The maximum length allowed for an array is 4,294,967,295.

Suppose a declaration such as var num = [1,2,3,4] will give you an array as shown below:

Accessing Array elements


Arrays are indexed from 0. The array name followed by the subscript is used for referring an array
element.

Syntax
1. array_name[subscript];

Example
1. var num;
2. num = [2,4,6,8];
3. console.log(num[0]);
4. console.log(num[1]);

Output

2
4

Array Constructor
We can also create an array by using the array constructor. Array constructor can be passed as:

o A list of values separated by comma or,


o A numeric value which indicates the size of array

The following example will show you the illustration for the same:

Example - Single Numeric Value


1. var num = new Array(5); // This single numeric value indicates the size of array.
2. var i;
3. for(i=0;i<num.length;i++){
4. num[i]=i*5;
5. console.log(num[i]);
6. }

Output

0
5
10
15
20

Example - Comma Separated Values


1. var num = new Array(1,2,3,4,5);
2. var i;
3. for(i=0;i<num.length;i++){
4. console.log(num[i]);
5. }

Output

1
2
3
4
5

JavaScript Arrays
JavaScript supports the following categories of arrays.

o Multidimensional array
o Passing arrays to functions
o Return array from functions

ES6 Multidimensional Arrays


ES6 also supports the multidimensional array concept. A multidimensional array can be defined as an
array reference to another array for its value.

Multidimensional arrays are not directly provided in JavaScript. If you need to create a
multidimensional array, you have to do it by using the one-dimensional array.

We can also say that a two-dimensional array is the simplest form of a multidimensional array.

Declaration

The following syntax illustrates you how to declare two-dimensional array in JavaScript.
1. var array_name = [[value1,value2,value3],[val1,val2,val3]];

Accessing of Two-dimensional element of array

1. var array_name[initial_array_index][referenced_array_index]

Example

1. var multi = [[2,3,4],[4,9,16]]


2. console.log(multi[0][0])
3. console.log(multi[0][1])
4. console.log(multi[0][2])
5. console.log(multi[1][0])
6. console.log(multi[1][1])
7. console.log(multi[1][2])

Output

2
3
4
4
9
16

Passing Array to function


Passing array as an argument to a function, you have to specify the array name (a reference to an
array) without brackets. Let us try to understand it with the following example.

Example

1. var rainbow = new Array["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];
2. function show(rainbow) {
3. for(var i = 0;i<rainbow.length;i++) {
4. console.log(rainbow[i])
5. }
6. }
7. show(rainbow)

Output

Violet
Indigo
Blue
Green
Yellow
Orange
Red

Return Array from function


It allows a function to return an array.
Example

1. function show() {
2. return new Array("Blue", "Red", "Green", "Yellow")
3. }
4. var colors = show()
5. for(var i in colors) {
6. console.log(colors[i])
7. }

Output

Blue
Red
Green
Yellow

Array methods
Array methods in ES6 are useful to work with data stored in arrays. Array methods are used to perform
complex tasks easily with arrays.

You can learn more about array methods by clicking on this link ES6 Array methods

Destructuring Assignment
ES6 provides us a new feature called a destructuring assignment, which allows us to extract specific
items from objects and arrays and place them into variables by using a shorthand syntax. It not only
helps to reduce the code but also change the way of structuring the code. It is the process of breaking
a structure.

Destructuring assignment is a JavaScript expression that makes it possible to extract data from arrays,
maps, sets, and from the properties of the object in distinct variables.

Array destructuring
Destructuring means to break down a complex structure into simpler parts. With the syntax of
destructuring, you can extract smaller fragments from objects and arrays. It can be used for
assignments and declaration of a variable.

To learn more about array destructuring, you can click on this link ES6 Array destructuring.

Object destructuring
It is similar to array destructuring except that instead of values being pulled out of an array, the
properties (or keys) and their corresponding values can be pulled out from an object.

To learn more about object destructuring, you can click on this link ES6 Object destructuring.

ES6 Array methods


Some new array methods are introduced in ES6, such as Array.of(), Array.from(), and many more.
The array methods introduced in ES6 are tabulated below.

S.no. Methods Description

1. Array.from() It converts array-like values and iterable values into arrays.

2. Array.of() It creates an instance from a variable number of arguments


instead of the number of arguments or type of arguments.

3. Array.prototype.copyWithin() It copies the part of an array to a different location within


the same array.

4. Array.prototype.find() It finds a value from an array, based on the specific criteria


that are passed to this method.

5. Array.prototype.findIndex() The Array.prototype.findIndex() returns the index of the first


element of the given array that satisfies the given condition.

6. Array.prototype.entries() It returns an array iterator object, which can be used to loop


through keys and values of arrays.

7. Array.prototype.keys() It returns an array iterator object along with the keys of the
array.

8. Array.prototype.values() it provides the value of each key.

9. Array.prototype.fill() It fills the specified array elements with a static value

Let us understand these new array methods.

Array.from()
The general function of this method is to enable new array creation from an array-like object. It
converts array-like values and iterable values (such as set and map) into arrays.

Syntax

1. Array.from(object, mapFunction, thisValue)

Let's understand the parameter values of this function.

object: This parameter value is always required. It is the object to convert to an array.
mapFunction: It is optional. It is a map function to call on each item of the array.

thisValue: It is also optional. It is a value to use as this when executing the mapFunction.

Example

1. let name = Array.from('javaTpoint')


2.
3. console.log(name)

Output

[
'j', 'a', 'v', 'a',
'T', 'p', 'o', 'i',
'n', 't'
]

Array.of()
In ES5, when a single numeric value gets passed in the array constructor, then it will create an array of
that size. Array.of() is a new way of creating an array which fixes this behavior of ES5.

By using this method, if you are creating an array only with a single numeric value, then it will create
an array only with that value instead of creating the array of that size.

Example

1. let name = Array.of(42)


2.
3. console.log(name)
4. console.log(name.length)

Output

[ 42 ]
1

Array.prototype.copyWithin()
It is an interesting method that is added to the library of array methods in ES6. This method copies the
part of an array to a different location within the same array.

It returns the modified array without any modification in its length.

Note: Instead of adding more items to the array, this method only overwrites the elements of the
original array.

Syntax

1. array.copyWithin(target, start, end)


Let's understand the parameters of this method.

target: It is always required. It is the index position to copy the elements.

start: It is an optional parameter. It refers to the index position to start copying the elements. Its
default value is 0. If the value of this parameter is negative, then start will be counted from the end.

end: It is also an optional parameter. It refers to the index position to stop copying the elements. Its
default value is the length of the array.

Example

Let's understand the example of this method with various possibilities.

1. const num = [1,2,3,4,5,6,7,8,9,10];


2. const num1 = [1,2,3,4,5,6,7,8,9,10];
3. const num2 = [1,2,3,4,5,6,7,8,9,10];
4. console.log(num.copyWithin(1,3,5));
5. console.log(num1.copyWithin(1,3)); //omitting the parameter end
6. console.log(num2.copyWithin(1)); //omitting the parameters start and end

Output

[
1, 4, 5, 4, 5,
6, 7, 8, 9, 10
]
[
1, 4, 5, 6, 7,
8, 9, 10, 9, 10
]
[
1, 1, 2, 3, 4,
5, 6, 7, 8, 9
]

Array.prototype.find()
It is another new function of ES6. It finds a value from an array, based on the specific criteria that are
passed to this method. It returns the first element value that satisfies the given condition.

Syntax

1. array.find(callback(currentValue, index, arr),thisValue)

Let's understand the parameters of this method.

callback: It represents the function that executes every element.

currentValue:I t is the required parameter. It is the value of the current element.

index: it is an optional parameter. It is the array index of the current element.

arr: It is also an optional parameter. It is the array on which the find() operated.

thisValue: It is optional. It is a value that is used as this while using callback.


Example

1. var arr=[5,22,19,25,34];
2. var result=arr.find(x=>x>20);
3. console.log(result);

Output

22

Note: ES6 find() method is not similar to the ES5 filter() method because the filter() method always
returns an array of matches (return multiple matches), but find() method always returns the actual
statement.

Array.prototype.findIndex()
The Array.prototype.findIndex() method returns the index of the first element of the given array that
satisfies the given condition. If no element satisfies the condition, then it returns -1.

Syntax

1. array.findIndex(callback(value,index,arr),thisArg)

Example

1. var arr=[5,22,19,25,34];
2. var result=arr.findIndex(x=>x>20);
3. console.log(result)

Output

Array.prototype.entries()
This method returns an array iterator object, which can be used to loop through keys and values of
arrays.

Entries will return an array of arrays, in which every child array is an array of [index, value].

Syntax

1. array.entries()

Example

1. var colours = ["Red", "Yellow", "Blue", "Black"];


2. var show = colours.entries();
3.
4. for (i of show) {
5. console.log(i);
6. }

Output

[ 0, 'Red' ]
[ 1, 'Yellow' ]
[ 2, 'Blue' ]
[ 3, 'Black' ]

In above example, we can also use the spread operator instead of for…of loop which will give you same
result.

1. var colours = ["Red", "Yellow", "Blue", "Black"];


2. var show = colours.entries();
3. console.log(...show);

Output

[ 0, 'Red' ] [ 1, 'Yellow' ] [ 2, 'Blue' ] [ 3, 'Black' ]

Array.prototype.keys()
This method works similarly to the Array.entries() method. As its name implies, it is used to return
an array iterator object along with the keys of the array.

Syntax

1. array.keys()

Example

1. var colours = ["Red", "Yellow", "Blue", "Black"];


2. var show = colours.keys();
3. console.log(...show);

Output

0 1 2 3

Array.prototype.values()
This method is similar to Array.keys() and Array.entries() except that it provides the value of each
key.

Syntax

1. array.values()

Example

1. var colours = ["Red", "Yellow", "Blue", "Black"];


2. var show = colours.values();
3. console.log(...show);

Output

Red Yellow Blue Black

Array.prototype.fill()
This method fills the specified array elements with a static value. The value can be used to fill a part of
an array or to fill the entire array. It modifies the original array.

You can specify the position of the start and end the filling. If not specified, then all elements will be
filled.

Syntax

1. array.fill(value, start, end)

Parameter Values

value: It is a static value to fill the array. It is always required.

start: It is the index to start filling the array. It is optional, and its default value is 0.

end: It is the index to stop filling the array. It is also optional, and its default value is the length of the
array.

Example

1. var colours = ["Red", "Yellow", "Blue", "Black"];


2. var show = colours.fill("Green",2,4);
3. console.log(...show);

Output

Red Yellow Green Green

JavaScript Array Methods

S.no. Methods Description

1. concat() This method returns a new array object which contains two or more
merged arrays.

2. join() This method joins the array elements as a string.

3. pop() This method is used to remove and return the last element of an array.
4. push() The push() adds one or more elements at the end of an array.

5. reverse() This method reverses the elements of the given array.

6. shift() This method is used to remove and return the first element of an array.

7. slice() This method returns a new array that contains a copy of the part of the
given array.

8. sort() This method returns the element of the given array in sorted order.

9. toString() This method returns the strings with all array elements separated by
commas.

10. unshift() The unshift() adds one or more elements at the starting of the given
array.

11. splice() This method adds/removes the elements to/from the given array.

12. every() This method is used to determine whether all the elements of an array
satisfy the provided function conditions.

13. filter() This method returns the new array, which contains the elements that
pass the provided function conditions.

14. forEach() This method invokes the provided function once for each element of an
array.

15. isArray() This method determines whether an object is an array or not. It returns
true if the object is an array and returns false if not.

16. indexOf() It searches the specified element in the given array and returns the index
of the first match.

17. lastIndexOf() It searches the specified element in the given array and returns the index
of the last match.

18. map() It calls the specified function for every array element and returns the new
array
19. reduce() This method reduces the array to a single value.

20. some() This method returns a Boolean value. Returns true if an array element
passes the test else it returns false.

ES6 Array destructuring


Destructuring means to break down a complex structure into simpler parts. With the syntax of
destructuring, you can extract smaller fragments from objects and arrays. It can be used for
assignments and declaration of a variable.

Destructuring is an efficient way to extract multiple values from data that is stored in arrays or objects.
When destructuring an array, we use their positions (or index) in an assignment.

Let us try to understand the array destructuring by using some illustrations:

Example
1. var arr = ["Hello", "World"]
2.
3. // destructuring assignment
4. var [first, second] = arr;
5.
6. console.log(first); // Hello
7. console.log(second); // World

In the above example, the left-hand side of destructuring assignment is for defining what values are
required to unpack from sourced variable.

Output

Hello
World

Let us take another example of array destructuring.

Example
1. var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];
2.
3. // destructuring assignment
4. var[color1, color2, color3] = colors;
5.
6. console.log(color1); // Violet
7. console.log(color2); // Indigo
8. console.log(color3); // Blue

Output

Violet
Indigo
Blue

Example
If you want to choose random elements from the given array then in array destructuring you can
perform it as follows:

1. var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];


2.
3. // destructuring assignment
4. var[color1, ,color3, ,color5] = colors; //Leave space for unpick elements
5. console.log(color1); // Violet
6. console.log(color3); // Blue
7. console.log(color5); // Yellow

In the above example, we have defined an array named colors which has seven elements. But we
have to show three random colors from the given array that are Violet, Blue, and Yellow. These
array elements are in positions 0, 2, and 4.

During destructuring, you have to leave the space for unpick elements, as shown in the above
example. Otherwise, you will get unintended results.

Output

Violet
Blue
Yellow

Note: We cannot use numbers for destructuring. Using numbers will throw an error because numbers
cannot be the name of the variable.

Array destructuring and Rest operator


By using the rest operator (…) in array destructuring, you can put all the remaining elements of an
array in a new array.

Let us try to understand it with an example.

Example
1. var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];
2.
3. // destructuring assignment
4. var [a,b,...args] = colors;
5. console.log(a);
6. console.log(b);
7. console.log(args);

Output
Violet
Indigo
[ 'Blue', 'Green', 'Yellow', 'Orange', 'Red' ]

Array destructuring and Default values


If you are taking a value from the array and that value is undefined, then you can assign a default
value to a variable.

Example
1. var x, y;
2.
3. [x=50, y=70] = [100];
4. console.log(x); // 100
5. console.log(y); // 70

Output

100
70

Swapping Variables
The values of the two variables can be swapped in one destructuring expression. The array
destructuring makes it easy to swap the values of variables without using any temporary variable.

Example
1. var x = 100, y = 200;
2. [x, y] = [y, x];
3. console.log(x); // 200
4. console.log(y); // 100

Output

200
100

Parsing returned array from functions


A function can return an array of values. It is always possible to return an array from a function, but
array destructuring makes it more concise to parse the returned array from functions.

Let us understand it with an example.

Example
1. function array() {
2. return [100, 200, 300];
3. }
4.
5. var [x, y, z] = array();
6.
7. console.log(x); // 100
8. console.log(y); // 200
9. console.log(z); // 300

In the above example, we have defined the array() function, which returns an array containing three
elements. We used array destructuring to destructure the above array elements into specific elements
x, y, and z in a single line of code.

Output

100
200
300

ES6 Objects
Objects are the collection of key/value pairs that can be modified throughout the lifecycle of an object
as similar to hash map or dictionary. Objects allow us to define custom data types in JavaScript.

Unlike primitive data types, we can represent complex or multiple values using objects. The values can
be the array of objects or the scalar values or can be the functions. Data inside objects are unordered,
and the values can be of any type.

An object can be created by using curly braces {...} along with an optional properties list. The property
is a "key:value" pair, where the key is a string or a property name, and the value can be anything.

Syntax
There are two syntaxes to create an empty object:

o By using object literal


o By using object constructor

1. var user = {}; // 'object literal' syntax


2. var name = new Object(); //'object constructor' syntax

Object Literal Syntax Extensions in ES6


Similar to primitive data types, objects also have a literal syntax. Object literal is one of the widely
used patterns to create objects in JavaScript.

ES6 makes the object literal more concise and robust by extending the syntax in different ways.

Let us see the shorthand for object property initializer.

Object Property Initializer


Before ES6, the object literal is a collection of name-value pairs. For example,
In ES5

1. function user(name, division) {


2. return {
3. name: name,
4. divison: division
5. };
6. }

The above function user() takes two arguments, which are name and division, and returns a new
object literal having two properties name and division. The property name and division take the
values of the function parameters.

The above syntax looks repetitive because the name and division mentioned twice in keys and values
of properties.

The syntax in ES6 eliminates the duplication when an object property is the same as the name of a
local variable. Let's understand this by rewriting the above user() function in ES6.

In ES6

1. function user(name, division) {


2. return {
3. name,
4. divison
5. };
6. }

In the above code snippet, the JavaScript engine assigns the value of name and division arguments
to the name and division properties.

Similarly, we can construct an object literal by local variables, as shown in the following example:

Example

1. let uname = 'Anil',


2. udivision = 'First';
3.
4. let user = {
5. uname,
6. udivision
7. };
8. console.log(user.uname);
9. console.log(user.udivision);

Output

Anil
First

By using this shorthand syntax, the JavaScript engine looks in the scope for a variable with the same
name. If it is found, then the value of the variable is assigned to the property. But if it is not found,
then a reference error will occur.
Computed property name
Before ES6, we could use the square brackets [] to enable the computed property names for the object
properties. Square bracket notation allows us to use variables and string literals as the name of the
property.

ES6 introduced a new feature 'computed property names,' which is a part of object literal syntax,
and it uses the square bracket [] notation. It allows us to put an expression within the square
brackets [] that will be computed and used as the name of the property.

Let us understand computed property names by using the following example:

In ES5

1. var emp = {
2. id : 101,
3. name : 'Amit'
4. }
5. var department = 'dep_name';
6. emp[department]='Sales';
7. console.log(emp);

Output

{ id: 101, name: 'Amit', dep_name: 'Sales' }

In ES6

1. var department = 'dep_name';


2. var emp = {
3. id : 102,
4. name : 'Anil',
5. [department]:'Production'
6. }
7. console.log(emp);

Output

{ id: 102, name: 'Anil', dep_name: 'Production' }

Concise method syntax


Before ES6, defining a method for an object literal, we must have to specify the name and definition of
a complete function as represented in the following example:

Example

1. let user = {
2. firstName : "Sunil",
3. lastName : "Kumar",
4. fullName : function(){
5. return this.firstname + " " + this.lastName;
6. }
7. };

ES6 uses shorthand syntax, which is also known as the concise method syntax for making a method
of the object literal concise by removing the colon (:) and the function keyword.

Let's use this syntax on the above example by rewriting the object user.

1. let user = {
2. firstName : "Sunil",
3. lastName : "Kumar",
4. fullName(){
5. return this.firstname + " " + this.lastName;
6. }
7. };

Merge objects in ES6


It is possible to merge two JavaScript objects in ES6 by using two methods, which are listed below:

o Object.assign() method
o Object spread syntax method

Let us try to understand these two methods.

By using Object.assign() method


This method is used for copying the values and properties from one or more source object to a target
object. It returns the target object, including properties and values copied from the target object.

Syntax

1. Object.assign(target, sources)

Example

1. var obj1 = {1 : "Hello", 2: "World"};


2. var obj2 = { 3 : "Welcome", 4: "to"};
3. var obj3 = { 5 : "javaTpoint"}
4.
5. // Using Object.assign()
6. var final_obj = Object.assign(obj1, obj2, obj3);
7. console.log(final_obj);

Output

{
'1': 'Hello',
'2': 'World',
'3': 'Welcome',
'4': 'to',
'5': 'javaTpoint'
}

Object Cloning
Cloning is the process of copying an object from one variable to another variable. We can clone an
object by using the object.assign() method.

Let us try to understand it with the following example:

Example

1. let obj1 = {
2. name: 'Anil',
3. age: 22
4. };
5. let cloneobj = Object.assign({}, obj1);
6.
7. cloneobj.age = 32;
8.
9. console.log(obj1);
10. console.log(cloneobj);

Output

{ name: 'Anil', age: 22 }


{ name: 'Anil', age: 32 }

By using Object spread syntax


It is widely used in a variable array where multiple values are expected. As the objects in JavaScript
are key-value paired entities, we can merge them into one by using the spread operator.

Syntax

1. var new_obj = [...obj1, ...obj2, ...]

Example

1. var obj1 = {1 : "Hello", 2: "World"};


2. var obj2 = { 3 : "Welcome", 4: "to"};
3. var obj3 = { 5 : "javaTpoint"}
4.
5. var final_obj = {...obj1, ...obj2, ...obj3};
6. console.log(final_obj);

Output

{
'1': 'Hello',
'2': 'World',
'3': 'Welcome',
'4': 'to',
'5': 'javaTpoint'
}

Delete properties
It can be possible to remove or delete a property by using the delete operator. Let us understand how
to remove a property by using the following example.

Example

1. var obj = new Object;


2. obj.a = 50;
3. obj.b = 200;
4.
5.
6. delete obj.a;
7. console.log (obj.a);

Output

undefined

Object Destructuring
It is similar to array destructuring except that instead of values being pulled out of an array, the
properties (or keys) and their corresponding values can be pulled out from an object.

When destructuring the objects, we use keys as the name of the variable. The variable name must
match the property (or keys) name of the object. If it does not match, then it receives
an undefined value. This is how JavaScript knows which property of the object we want to assign.

To learn more about object destructuring, you can click on this link ES6 Object destructuring.

Object destructuring
It is similar to array destructuring except that instead of values being pulled out of an array, the
properties (or keys) and their corresponding values can be pulled out from an object.

When destructuring the objects, we use keys as the name of the variable. The variable name must
match the property (or keys) name of the object. If it does not match, then it receives
an undefined value. This is how JavaScript knows which property of the object we want to assign.

In object destructuring, the values are extracted by the keys instead of position (or index).

First, try to understand the basic assignment in object destructuring by using the following example.

Example - Simple assignment


1. const num = {x: 100, y: 200};
2. const {x, y} = num;
3.
4. console.log(x); // 100
5. console.log(y); // 200

Output

100
200

Let us understand the basic object destructuring assignment.

Example - Basic Object destructuring assignment


1. const student = {name: 'Arun', position: 'First', rollno: '24'};
2. const {name, position, rollno} = student;
3. console.log(name); // Arun
4. console.log(position); // First
5. console.log(rollno); // 24

Output

Arun
First
24

Object destructuring and default values


Like array destructuring, a default value can be assigned to the variable if the value unpacked from the
object is undefined. It can be clear from the following example.

Example
1. const {x = 100, y = 200} = {x: 500};
2.
3. console.log(x); // 500
4. console.log(y); // 200

In the above example, the variables x and y have default values 100 and 200. Then, the variable x is
reassigned with a value of 500. But the variable y is not reassigned, so it retains its original value. So,
instead of getting 100 and 200 in output, we will get 500 and 200.

Output

500
200

Assigning new variable names


We can assign a variable with a different name than the property of the object. You can see the
illustration for the same as follows:

Example
1. const num = {x: 100, y: 200};
2. const {x: new1, y: new2} = num;
3.
4. console.log(new1); //100
5. console.log(new2); //200

In the above example, we have assigned the property name as x and y to a local
variable, new1, and new2.

Output

100
200

Assignment without declaration


if the value of the variable is not assigned when you declare it, then you can assign its value during
destructuring. You can see the illustration for the same as follows:

Example
1. let name, division;
2. ({name, division} = {name: 'Anil', division: 'First'});
3. console.log(name); // Anil
4. console.log(division); // First

In the above example, it is to be noted that the use of parentheses () around the assignment
statement is mandatory when using variable destructuring assignment without a declaration.
Otherwise, the syntax will be invalid.

Output

Anil
First

Object destructuring and rest operator


By using the rest operator (…) in object destructuring, we can put all the remaining keys of an object in
a new object variable.

Let us try to understand it with an example.

Example
1. let {a, b, ...args} = {a: 100, b: 200, c: 300, d: 400, e: 500}
2. console.log(a);
3. console.log(b);
4. console.log(args);

Output

100
200
{ c: 300, d: 400, e: 500 }
Assigning new variable names and providing default values
simultaneously
A property that is unpacked from an object can be assigned to a variable with a different name. And
the default value is assigned to it in case the unpacked value is undefined.

Example
1. const {a:num1=100, b:num2=200} = {a:300};
2. console.log(num1); //300
3. console.log(num2); //200

Output

300
200

ES6 Map
ES6 is a series of new features that are added to the JavaScript. Prior to ES6, when we require the
mapping of keys and values, we often use an object. It is because the object allows us to map a key to
the value of any type.

ES6 provides us a new collection type called Map, which holds the key-value pairs in which values of
any type can be used as either keys or values. A Map object always remembers the actual insertion
order of the keys. Keys and values in a Map object may be primitive or objects. It returns the new or
empty Map.

Maps are ordered, so they traverse the elements in their insertion order.

Syntax
For creating a new Map, we can use the following syntax:

1. var map = new Map([iterable]);

The Map () accepts an optional iterable object, whose elements are in the key-value pairs.

Map Properties

S.no. Properties Description

1. Map.prototype.size This property returns the number of key-value pairs in the Map

Let us understand the above property of Map object in brief.

Map.prototype.size
It returns the number of elements in the Map object.
Syntax

1. Map.size

Example

1. var map = new Map();


2. map.set('John', 'author');
3. map.set('arry', 'publisher');
4. map.set('Mary', 'subscriber');
5. map.set('James', 'Distributor');
6.
7. console.log(map.size);

Output

Map Methods
The Map object includes several methods, which are tabulated as follows:

S.no. Methods Description

1. Map.prototype.clear() It removes all the keys and values pairs from the M

2. Map.prototype.delete(key) It is used to delete an entry.

3. Map.prototype.has(value) It checks whether or not the corresponding key is

4. Map.prototype.entries() It is used to return a new iterator object that has a


value pairs for every element in the Map object in

5. Map.prototype.forEach(callbackFn[, It executes the callback function once, which is e


thisArg]) element in the Map.

6. Map.prototype.keys() It returns an iterator for all keys in the Map.

7. Map.prototype.values() It returns an iterator for every value in the Map.

Weak Maps
Weak Maps are almost similar to normal Maps except that the keys in weak maps must be objects. It
stores each element as a key-value pair where keys are weakly referenced. Here, the keys are objects,
and the values are arbitrary values. A Weak Map object only allows the keys of an object type. If there
is no reference to a key object, then they are targeted to garbage collection. In weak Map, the keys are
not enumerable. So, there is no method to get the list of keys.

A weak map object iterates its elements in the insertion order. It only includes delete(key),
get(key), has(key) and set(key, value) method.

Let us try to understand the illustration of the weak Map.

Example
1. 'use strict'
2. let wp = new WeakMap();
3. let obj = {};
4. console.log(wp.set(obj,"Welcome to javaTpoint"));
5. console.log(wp.has(obj));

Output

WeakMap { <items unknown> }


true

The for...of loop and Weak Maps


The for...of loop is used to perform an iteration over keys, values of the Map object. The following
example will illustrate the traversing of the Map object by using a for...of loop.

Example
1. 'use strict'
2. var colors = new Map([
3. ['1', 'Red'],
4. ['2', 'Green'],
5. ['3', 'Yellow'],
6. ['4', 'Violet']
7. ]);
8.
9. for (let col of colors.values()) {
10. console.log(col);
11. }
12.
13. console.log(" ")
14.
15. for(let col of colors.entries())
16. console.log(`${col[0]}: ${col[1]}`);

Output

Red
Green
Yellow
Violet
1: Red
2: Green
3: Yellow
4: Violet

Iterator and Map


An iterator is an object, which defines the sequence and a return value upon its termination. It allows
accessing a collection of objects one at a time. Set and Map both include the methods that return an
iterator.

Iterators are the objects with the next() method. When the next() method gets invoked, the iterator
returns an object along with the "value" and "done" properties.

Let us try to understand some of the implementations of iterator along with the Map object.

Example-1
1. 'use strict'
2. var colors = new Map([
3. ['1', 'Red'],
4. ['2', 'Green'],
5. ['3', 'Yellow'],
6. ['4', 'Violet']
7. ]);
8.
9. var itr = colors.values();
10. console.log(itr.next());
11. console.log(itr.next());
12. console.log(itr.next());

Output

{ value: 'Red', done: false }


{ value: 'Green', done: false }
{ value: 'Yellow', done: false }

Example-2
1. 'use strict'
2. var colors = new Map([
3. ['1', 'Red'],
4. ['2', 'Green'],
5. ['3', 'Yellow'],
6. ['4', 'Violet']
7. ]);
8. var itr = colors.entries();
9. console.log(itr.next());
10. console.log(itr.next());
11. console.log(itr.next());
Output

{ value: [ '1', 'Red' ], done: false }


{ value: [ '2', 'Green' ], done: false }
{ value: [ '3', 'Yellow' ], done: false }

Example-3
1. 'use strict'
2. var colors = new Map([
3. ['1', 'Red'],
4. ['2', 'Green'],
5. ['3', 'Yellow'],
6. ['4', 'Violet']
7. ]);
8.
9. var itr = colors.keys();
10. console.log(itr.next());
11. console.log(itr.next());
12. console.log(itr.next());

Output

{ value: '1', done: false }


{ value: '2', done: false }
{ value: '3', done: false }

ES6 Set
A set is a data structure that allows you to create a collection of unique values. Sets are the collections
that deal with single objects or single values.

Set is the collection of values similar to arrays, but it does not contain any duplicates. It allows us to
store unique values. It supports both primitive values and object references.

As similar to maps, sets are also ordered, i.e., the elements in sets are iterated in their insertion order.
It returns the set object.

Syntax
1. var s = new Set("val1","val2","val3");

Let us understand the concept of set by using the following example:

Example
1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);
2. console.log(colors);

All the elements of a Set must be unique. Therefore the set colors in the above example only contain
four distinct elements. We will get the following output after the successful execution of the above
code.
Output

Set { 'Green', 'Red', 'Orange', 'Yellow' }

Let us see the properties and methods of the Set.

Set Properties

S.no. Properties Description

1. Set.size This property returns the number of values in the set object.

Set.size
This property of the Set object returns the value that represents the number of elements in the Set
object.

Example

1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


2. console.log(colors.size);
3. console.log(colors);

Output

4
Set { 'Green', 'Red', 'Orange', 'Yellow' }

Set Methods
The set object includes several methods, which are tabulated as follows:

S.no. Methods Description

1. Set.prototype.add(value) It appends a new element to the given value

2. Set.prototype.clear() It removes all the elements from the set obje

3. Set.prototype.delete(value) It removes the element which is associated w


corresponding value.

4. Set.prototype.entries() It returns a new iterator object, which contai


element in the Set object in insertion order.
5. Set.prototype.forEach(callbackFn[, It executes the callback function once.
thisArg])

6. Set.prototype.has(value) This method returns true when the passed va

7. Set.prototype.values() It returns the new iterator object, which cont


each element in the Set, in insertion order.

Now, we are going to understand the above methods of the Set object in detail.

Set.prototype.add(value)
This method is used to append a new element with the existing value to the Set object.

Example

1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


2. colors.add('Violet');
3. colors.add('Indigo');
4. colors.add('Blue');
5. colors.add('Violet');
6. console.log(colors.size);
7. console.log(colors);

Output

7
Set { 'Green', 'Red', 'Orange', 'Yellow', 'Violet', 'Indigo', 'Blue' }

Set.prototype.clear()
It clears all the objects from the sets.

Example

1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


2. colors.add('Violet');
3. colors.add('Indigo');
4. colors.add('Blue');
5. colors.add('Violet');
6. colors.clear()
7. console.log(colors.size);

Output

Set.prototype.delete(value)
This method is used to remove the corresponding passed value from the set object.

Example

1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


2. colors.add('Violet');
3. colors.add('Indigo');
4. colors.add('Blue');
5. colors.add('Violet');
6. colors.delete('Violet');
7. console.log(colors.size);
8. console.log(colors);

Output

6
Set { 'Green', 'Red', 'Orange', 'Yellow', 'Indigo', 'Blue' }

Set.prototype.entries()
It returns the object of a new set iterator. It contains an array of values for each element. It maintains
the insertion order.

Example

1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


2. colors.add('Violet');
3. colors.add('Indigo');
4. colors.add('Blue');
5. colors.add('Violet');
6. var itr = colors.entries();
7. for(i=0;i<colors.size;i++) {
8. console.log(itr.next().value);
9. }

Output

[ 'Green', 'Green' ]
[ 'Red', 'Red' ]
[ 'Orange', 'Orange' ]
[ 'Yellow', 'Yellow' ]
[ 'Violet', 'Violet' ]
[ 'Indigo', 'Indigo' ]
[ 'Blue', 'Blue' ]

Set.prototype.forEach(callbackFn[, thisArg])
It executes the specified callback function once for each Map entry.

Example

1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


2. colors.add('Violet');
3. colors.add('Indigo');
4. colors.add('Blue');
5. colors.add('Violet');
6. function details(values){
7. console.log(values);
8. }
9. colors.forEach(details);

Output

Green
Red
Orange
Yellow
Violet
Indigo
Blue

Set.prototype.has(value)
It returns the Boolean value that indicates whether the element, along with the corresponding value,
exists in a Set object or not.

Example

1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


2. colors.add('Violet');
3. colors.add('Indigo');
4. colors.add('Blue');
5. colors.add('Violet');
6. console.log(colors.has('Indigo'));
7. console.log(colors.has('Violet'));
8. console.log(colors.has('Cyan'));

Output

true
true
false

Set.prototype.values()
It returns a new iterator object that includes the values for each element in the Set object in the
insertion order.

Example

1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


2. colors.add('Violet');
3.
4. var val = colors.values();
5. console.log(val.next().value);
6. console.log(val.next().value);
7. console.log(val.next().value);
8. console.log(val.next().value);
9. console.log(val.next().value);

Output

Green
Red
Orange
Yellow
Violet

Weak Set
It is used to store the collection of objects. It is similar to the Set object, so it also cannot store
duplicate values. Similar to weak maps, weak sets cannot be iterated. Weak sets can contain only
objects which may be garbage collected.

Weak set only includes add(value), delete(value) and has(value) methods of Set object.

Example
1. 'use strict'
2. let ws = new WeakSet();
3. let obj = {msg:"Welcome Back!"};
4. ws.add(obj);
5. console.log(ws.has(obj));
6. ws.delete(obj);
7. console.log(ws.has(obj));

Output

true
false

Iterators
An iterator is an object which defines the sequence and a return value upon its termination. It allows
accessing a collection of objects one at a time. Set and Map both include the methods that return an
iterator.

Iterators are the objects with the next() method. When the next() method gets invoked, the iterator
returns an object along with the 'value' and 'done' properties.

The 'done' is a Boolean which returns true after reading all of the elements in the collection.
Otherwise, it returns false.

Let's understand the implementations of iterator along with the Set object.

Example
1. let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);
2. var itr = colors.keys();
3. var itr1 = colors.entries();
4. var itr2 = colors.values();
5. console.log(itr.next());
6. console.log(itr1.next());
7. console.log(itr2.next());

Output

{ value: 'Green', done: false }


{ value: [ 'Green', 'Green' ], done: false }
{ value: 'Green', done: false }

ES6 Classes
Classes are an essential part of object-oriented programming (OOP). Classes are used to define the
blueprint for real-world object modeling and organize the code into reusable and logical parts.

Before ES6, it was hard to create a class in JavaScript. But in ES6, we can create the class by using
the class keyword. We can include classes in our code either by class expression or by using a class
declaration.

A class definition can only include constructors and functions. These components are together called
as the data members of a class. The classes contain constructors that allocates the memory to the
objects of a class. Classes contain functions that are responsible for performing the actions to the
objects.

Note: Instead of data properties, the body of the class only contains methods.

Syntax: Class Expression

1. var var_name = new class_name {


2. }

Syntax: Class Declaration

1. class Class_name{
2. }

Let us see the illustration for the class expression and class declaration.

Example - Class Declaration

1. class Student{
2. constructor(name, age){
3. this.name = name;
4. this.age = age;
5. }
6.
7. }
Example - Class Expression

1. var Student = class{


2. constructor(name, age){
3. this.name = name;
4. this.age = age;
5. }
6. }

Instantiating an Object from class


Like other object-oriented programming languages, we can instantiate an object from class by using
the new keyword.

Syntax

1. var obj_name = new class_name([arguements])

Example

1. var stu = new Student('Peter', 22)

Accessing functions
The object can access the attributes and functions of a class. We use the '.' dot notation
(or period) for accessing the data members of the class.

Syntax

1. obj.function_name();

Example

1. 'use strict'
2. class Student {
3. constructor(name, age) {
4. this.n = name;
5. this.a = age;
6. }
7. stu() {
8. console.log("The Name of the student is: ", this.n)
9. console.log("The Age of the student is: ",this. a)
10. }
11. }
12.
13. var stuObj = new Student('Peter',20);
14. stuObj.stu();

In the above example, we have declared a class Student. The constructor of the class contains two
arguments name and age, respectively. The keyword 'this' refers to the current instance of the class.
We can also say that the above constructor initializes two variables 'n' and 'a' along with the
parameter values passed to the constructor.

The function stu() in the class will print the values of name and age.

Output

The Name of the student is: Peter


The Age of the student is: 20

Note: Including a constructor definition is mandatory in class because, by default, every class has a
constructor.

The Static keyword


The static keyword is used for making the static functions in the class. Static functions are referenced
only by using the class name.

Example

1. 'use strict'
2. class Example {
3. static show() {
4. console.log("Static Function")
5. }
6. }
7. Example.show() //invoke the static method

Output

Static Function

Class inheritance
Before the ES6, the implementation of inheritance required several steps. But ES6 simplified the
implementation of inheritance by using the extends and super keyword.

Inheritance is the ability to create new entities from an existing one. The class that is extended for
creating newer classes is referred to as superclass/parent class, while the newly created classes are
called subclass/child class.

A class can be inherited from another class by using the 'extends' keyword. Except for the
constructors from the parent class, child class inherits all properties and methods.

Syntax

1. class child_class_name extends parent_class_name{


2. }

A class inherits from the other class by using the extends keyword.
Example

1. 'use strict'
2. class Student {
3. constructor(a) {
4. this.name = a;
5. }
6. }
7. class User extends Student {
8. show() {
9. console.log("The name of the student is: "+this.name)
10. }
11. }
12. var obj = new User('Sahil');
13. obj.show()

In the above example, we have declared a class student. By using the extends keyword, we can
create a new class User that shares the same characteristics as its parent class Student. So, we can
see that there is an inheritance relationship between these classes.

Output

The name of the student is: Sahil

Types of inheritance
Inheritance can be categorized as Single-level inheritance, Multiple inheritance, and Multi-level
inheritance. Multiple inheritance is not supported in ES6.

Single-level Inheritance
It is defined as the inheritance in which a derived class can only be inherited from only one base class.
It allows a derived class to inherit the behavior and properties of a base class, which enables the
reusability of code as well as adding the new features to the existing code. It makes the code less
repetitive.
Multiple Inheritance
In multiple inheritance, a class can be inherited from several classes. It is not supported in ES6.

Multi-level Inheritance
In Multi-level inheritance, a derived class is created from another derived class. Thus, a multi-level
inheritance has more than one parent class.

Let us understand it with the following example.

Example
1. class Animal{
2. eat(){
3. console.log("eating...");
4. }
5. }
6. class Dog extends Animal{
7. bark(){
8. console.log("barking...");
9. }
10. }
11. class BabyDog extends Dog{
12. weep(){
13. console.log("weeping...");
14. }
15. }
16. var d=new BabyDog();
17. d.eat();
18. d.bark();
19. d.weep();

Output

eating...
barking...
weeping...

Method Overriding and Inheritance


It is a feature that allows a child class to provide a specific implementation of a method which has been
already provided by one of its parent class.

There are some rules defined for method overriding -

o The method name must be the same as in the parent class.


o Method signatures must be the same as in the parent class.

Let us try to understand the illustration for the same:

Example

1. 'use strict' ;
2. class Parent {
3. show() {
4. console.log("It is the show() method from the parent class");
5. }
6. }
7. class Child extends Parent {
8. show() {
9. console.log("It is the show() method from the child class");
10. }
11. }
12. var obj = new Child();
13. obj.show();

In the above example, the implementation of the superclass function has changed in the child class.
You will get the following output after the successful execution of the above code:

Output

It is the show() method from the child class

The super keyword


It allows the child class to invoke the properties, methods, and constructors of the immediate parent
class. It is introduced in ECMAScript 2015 or ES6. The super.prop and super[expr] expressions are
readable in the definition of any method in both object literals and classes.

Syntax

super(arguments);

Example

In this example, the characteristics of the parent class have been extended to its child class. Both
classes have their unique properties. Here, we are using the super keyword to access the property
from parent class to the child class.

1. 'use strict' ;
2. class Parent {
3. show() {
4. console.log("It is the show() method from the parent class");
5. }
6. }
7. class Child extends Parent {
8. show() {
9. super.show();
10. console.log("It is the show() method from the child class");
11. }
12. }
13. var obj = new Child();
14. obj.show();

Output

It is the show() method from the parent class


It is the show() method from the child class

ES6 Strings
JavaScript string is an object which represents the sequence of characters. Generally, strings are used
to hold text-based values such as a person name or a product description.
In JavaScript, any text within the single or double quotes is considered as a string. There are two ways
for creating a string in JavaScript:

o By using a string literal


o By using string object (using the new keyword)

Let us elaborate both ways of creating a string in JavaScript.

By using a string literal


The string literals can be created by using either double quotes or by using single quotes. The syntax
for creating string literal is given below:

1. var stringname = "string value";

By using String object (using the new keyword)


Here, we will use a new keyword for creating the string object. The syntax for creating the string
object is given below:

1. var stringname = new String ("string literal");

String Properties
There are some properties of the string that are tabulated as follows:

S.no. Property Description

1. constructor It returns the constructor function for an object.

2. length It returns the length of the string.

3. prototype It allows us to add the methods and properties to an existing object.

Let us discuss the above string properties in detail.

JavaScript string constructor property


The constructor property returns the constructor function for an object. Instead of the name of the
function, it returns the reference of the function.

Syntax

1. string.constructor

Example

1. var str = new String("Hello World");


2. console.log("Value of str.constructor is: "+str.constructor);

Output

Value of str.constructor is: function String() { [native code] }

JavaScript string length property


As its name implies, this property returns the number of characters or the length of the string.

Syntax

1. string.length

Example

1. var str = new String("Hello World");


2. console.log("The number of characters in the string str is: "+str.length);

Output

The number of characters in the string str is: 11

JavaScript string prototype property


It allows us to add new methods and properties in an existing object type. It is a global property which
is available with almost all the objects of JavaScript.

Syntax

1. object.prototype.name = value;

Example

1. function student(name, qualification){


2. this.name = name;
3. this.qualification = qualification;
4. }
5. student.prototype.age = 20;
6. var stu = new student('Daniel Grint' , 'BCA');
7. console.log(stu.name);
8. console.log(stu.qualification);
9. console.log(stu.age);

Output

Daniel Grint
BCA
20

ES6 String Methods


There are four string functions available in ES6, which are tabulated as follows:
S.no. Methods Description

1. startsWith It determines whether a string begins with the characters of a specified


string.

2. endsWith It determines whether a string ends with the characters of a specified


string.

3. includes It returns true if the specified argument is in the string.

4. repeat It returns a new string repeated based on specified count arguments.

Let us discuss the above string methods in detail.

startsWith() method
It is a case-sensitive method, which determines whether the string begins with the specified string
characters or not. It returns true if the string begins with the characters and returns false if not.

Syntax

1. string.startsWith(searchValue, startPosition)

This method includes two parameters that are as follows:

o searchValue: It is the required parameter of this method. It includes the characters to be


searched for at the start of the string.
o startPosition: It is an optional parameter. Its default value is 0. It specifies the position in the
string at which to begin searching.

Example

1. var str = 'Welcome to javaTpoint :)';


2. console.log(str.startsWith('Wel',0));
3. console.log(str.startsWith('wel',0));

Output

true
false

endsWith() method
It is also a case-sensitive method that determines whether a string ends with the characters of the
specified string or not.
Syntax

1. string.endsWith(searchvalue, length)

The parameters of this method are defined as follows:

o searchValue: It is the required parameter that represents the characters to be searched at the
end of the string.
o length: It is an optional parameter. It is the length of the string that will be searched. If this
parameter is omitted, then the method will search in the full length of the string.

Example

1. var str = "Welcome to javaTpoint.";


2. console.log(str.endsWith("to", 10))
3. console.log(str.endsWith("To", 10))

Output

true
false

includes() method
It is a case-sensitive method that determines whether the string contains the characters of the
specified string or not. It returns true if the string contains characters and returns false if not.

Syntax

1. string.includes(searchValue, start)

Let's understand the parameters of this method.

o searchValue: It is a required parameter. It is the substring to search for.


o start: It represents the position where to start the searching in the string. Its default value is 0.

Example

1. let str = "hello world"


2.
3. console.log(str.includes('world',5));
4. console.log(str.includes('World', 11))

Output

true
false

repeat() method
It is used to build a new string that contains a specified number of copies of the string on which this
method has been called.
Syntax

1. string.repeat(count)

This function has a single argument.

o count: It is a required parameter that shows the number of times to repeat the given
string. The range of this parameter is from 0 to infinity.

Example

1. var str = "hello world";


2. console.log(str.repeat(5));

Output

hello worldhello worldhello worldhello worldhello world

JavaScript String Methods


Let us see some of the JavaScript methods that are tabulated below:

S.no. Methods Description

1. charAt() It provides the char value, which is present at the specified index.

2. charCodeAt() It provides the Unicode character value, which is present at the


specified index.

3. concat() It provides a combination of two or more strings.

4. match() It is used to search a specified regular expression in a given string


and return that expression if a match happens.

5. toString() It gives a string that represents the particular object.

6. indexOf() It gives the position of the char value, which is present in the given
string.

7. lastIndexOf() It gives the char value position in the given string by searching a
character from the last position.

8. replace() It replaces the given string with the specified replacement.


9. search() It searches a specific regular expression and returns its position if a
match occurs.

10. valueOf() It provides the primitive value of the string object.

11. slice() It is used to fetch the part of the given string.

12. split() It splits the string into the array of substring and returns the newly
created array.

13. substr() It fetches the part of the given string based on the specified length
and starting position.

14. substring() It fetches the part of the given string based on the specified index.

15. toLocaleLowerCase() It converts the given string into the lowercase letter based on the
current scale of the host.

16. toLocaleUpperCase() It converts given string into uppercase letters based on the current
scale of the host.

17. toLowerCase() It simply converts the given string into the lowercase letter.

18. toUpperCase() It simply converts the given string into the lowercase letter.

19. trim() It trims the white space from the left and right side of the string.

ES6 Template Literals


Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to
create multiline strings and perform string interpolation. Template literals are the string literals and
allow embedded expressions.

Before ES6, template literals were called as template strings. Unlike quotes in strings, template
literals are enclosed by the backtick (` `) character (key below the ESC key in QWERTY keyboard).
Template literals can contain placeholders, which are indicated by the dollar sign and curly
braces ($(expression}). Inside the backticks, if we want to use an expression, then we can place that
expression in the ($(expression}).

Syntax

1. var str = `string value`;


Multiline strings
In normal strings, we have to use an escape sequence \n to give a new line for creating a multiline
string. However, in template literals, there is no need to use \n because string ends only when it
gets backtick(`) character.

Let us try to understand it with the following example.

Example

1. // Without template literal


2. console.log('Without template literal \n multiline string');
3.
4. // With template literal
5. console.log(`Using template literal
6. multiline string`);

Output

Without template literal


multiline string
Using template literal
multiline string

String Interpolation
ES6 template literals support string interpolation. Template literals can use the placeholders for string
substitution. To embed expressions with normal strings, we have to use the ${} syntax.

Example -1

1. var name = 'World';


2. var cname = 'javaTpoint';
3. console.log(`Hello, ${name}!
4. Welcome to ${cname}`);

Output

Hello, World!
Welcome to javaTpoint

Let us see another example of string interpolation.

Example-2

1. var x = 10;
2. var y = 20;
3. console.log(`The product of the variables ${x} and ${y} is:
4. ${x*y}`);

Output

The product of the variables 10 and 20 is:


200

Tagged templates
Tagged templates are one of the more advanced form of template literals. Tagged template literals
allow us to parse template literals with a function.

The first argument of the tag function contains an array having string values, and the remaining
arguments are related to the expression. The writing of tagged literal is similar to the function
definition, but the difference occurs when the tagged literals get called. There are no
parentheses () required to call a literal.

Let us see the illustration for the tagged templates.

Example-1

1. function TaggedLiteral(str) {
2. console.log(str);
3. }
4.
5. TaggedLiteral `Hello World`;

Output

[ 'Hello World' ]

Example-2

We can also pass the values in a tagged literal. The value can be the result of some expression or the
value fetched from the variable. We can see the illustration for the same in the following code:

1. function TaggedLiteral(str, val1, val2) {


2. console.log(str);
3. console.log(val1+" "+val2);
4. }
5.
6. let text = 'Hello World';
7. TaggedLiteral`Colors ${text} ${10+30}`;

Output

[ 'Colors ', ' ', '' ]


Hello World 40

Raw Strings
The template literal raw method allows the accessing of raw strings as they were entered. In addition
to this, the string.raw() method exists for creating the raw strings as similar to the default template
function. It allows us to write the backslashes as we would in a regular expression literal.

The string.raw() method is used to show the strings without any interpretation of backslashed
characters. It is also useful to print windows sub-directory locations without require to use a lot of
backslashes.
Example

1. var rawText = String.raw`Hello \n World \n Welcome back! `


2. console.log(rawText)

Output

Hello \n World \n Welcome back!

String.fromCodePoint()
This method returns a string, which is created by using the specified sequence of Unicode code points.
It throws a RangeError if there is an invalid code point is passed.

Example

1. console.log(String.fromCodePoint(49))
2. console.log(String.fromCodePoint(80, 76))

Output

1
PL

ES6 Events
The interaction of JavaScript with HTML is handled through the events that occur when the browser or
the user manipulates the page. Events are the occurrences or actions that are recognized by the
software. A system or user can trigger them.

Events can be stated as a part of the DOM (Document Object Model) level 3. They occur when some
kind of interaction takes place on a web page. Every HTML elements contain a collection of events that
can trigger the code of JavaScript. Some of the common examples of events include clicking on a
button, clicking on a hyperlink, loading a webpage, etc.

Event Handlers
To react to events, you can assign a handler (a function which runs in case of an event occurs). The
event handler can be defined as a block of code that gets executed on the occurrence of an event. We
can define the processing of events in JavaScript by using the event handlers.

Let us try to understand the most commonly used events of HTML.

onclick Event type


It is one of the most frequently used event types that gets activated when the user clicks on a button.
In this event type, we can put a warning, validation, etc. With a click, the 'onclick' calls the
corresponding function() assigned to it.

Let's understand it with an example.

Example
1. <html>
2. <head>
3. <script type = "text/javascript">
4. function hello() {
5. alert ("Hello World");
6. }
7. </script>
8. </head>
9.
10. <body style="text-align:center;">
11. <p> Click the button</p>
12. <input type = "button" onclick = "hello()" value = "Click me " />
13. </body>
14. </html>

When you execute the above code in the browser, you will get the following output.

Output

After clicking the button, you will get an alert, as shown below.

onsubmit Event type


It occurs when you require to submit a form. When you click on the submit button, then
the 'onsubmit' calls the corresponding 'return function()' and takes the response from
the function() either in true or false. If the function() returns true, the form will be submitted.
Otherwise, it will not submit the data.

onmouseout and onmouseover


These events help you to create effects with the text and images. As the name implies,
the onmouseover event triggers when you bring the mouse over any element. The onmouseout
event triggers when you move the mouse out from the element.

Let us try to understand them by using the following example.

Example
1. <html>
2. <head>
3. <script type="text/javascript">
4. function mouseOver() {
5. document.getElementById("div1").style.color
6. = "blue";
7.
8. document.getElementById("div2").innerHTML
9. = "mouseOver triggered";
10.
11. document.getElementById("div2").style.color
12. = "green";
13. }
14. function mouseOut() {
15. document.getElementById("div1").style.color
16. = "magenta";
17.
18. document.getElementById("div2").innerHTML
19. = "mouseOut triggered";
20.
21. document.getElementById("div2").style.color
22. = "red";
23. }
24. </script>
25. </head>
26.
27. <body style="text-align:center;">
28.
29. <h1 id="div1" onmouseover="mouseOver()"
30. onmouseout="mouseOut()">
31. Bring your mouse inside it.
32. </h1>
33.
34. <h3>
35. Move your cursor on the above heading to see the result.
36. </h3>
37.
38. <h2><p id="div2"></p></h2>
39. </body>
40.
41. </html>

When you execute the above code in the browser, you will get the following output.

Output
Move your mouse over the first heading, and you will get:

Move your mouse out from the first heading, and you will get:

HTML5 Standard events


There are some of the commonly used HTML events that are listed in the following table.

Attributes Description

onabort It triggers on the abort event.

offline It gets trigger when the document goes offline.

onafterprint It triggers after the printing of the document.

onbeforeonload It triggers before the loading of the document.

onbeforeprint It triggers before the printing of the document.

onblur It triggers when the window loses the focus.

onchange It triggers when the element changes.


onclick It triggers when the mouse clicks.

oncontextmenu It triggers when the context menu gets triggered.

oncanplay It triggers when the media can start play.

oncanplaythrough It triggers when media plays till the end without any buffering or stopping.

ondbclick It triggers on the double-click of a mouse.

ondrag It triggers when the element is dragged.

ondrop It triggers when a dragged element is dropped.

ondragend It triggers when the drag operation gets end.

ondragenter It triggers when the element has dragged to drop target.

ondragleave It triggers when an element leaves a drop target.

ondragover It triggers when the element is being dragged over a drop target.

ondragstart It triggers at the starting of a drag operation.

ondurationchange It triggers when the media length is changed.

onended It triggers when the media reached the end.

omemptied It triggers when the resource element in media suddenly gets empty.

onfocus It triggers when the window gets focus.

onerror It triggers at the occurring of an error.

onformchange It triggers when the form gets change.

onforminput It triggers when the form gets input from the user.
onhaschange It triggers at the changing of a document.

oninput It triggers when the element gets input from the user.

oninvalid It triggers on an invalid element.

onkeyup It triggers when the key is released.

onkeydown It triggers when the key is pressed.

onkeypress It triggers when the key is released and pressed.

onload It triggers at the loading of the document.

onloadedmetadata It triggers when the media data and duration of the media element is loaded

onloadeddata It triggers when the data of media is loaded.

onmessage It triggers at the triggering of the message.

onloadstart It triggers when the browser starts the loading of media data.

onmousemove It triggers at the moving of the mouse pointer.

onmousedown It triggers at the pressing of the mouse button.

onmouseover It triggers when you move the mouse pointer over an element.

onmouseout It triggers when the mouse pointer moves out from the element.

onmouseup It triggers at the release of a mouse button.

onmousewheel It triggers when you rotate the wheel of the mouse.

ononline It triggers when the document is online.

onoffline It triggers when the document is offline.


onpageshow It triggers when the window gets visible.

onpagehide It triggers when the window is hidden.

onplay It triggers when the media data is going to start playing.

onplaying It triggers when the media data is playing.

onpause It triggers when the media data is paused.

onprogress It triggers when the browser fetches the media data.

onpopstate It triggers when the history of window changes.

onratechange It triggers when the playing rate of media data is changed.

onreadystatechange It triggers when the ready-state changes.

onredo It triggers when there is a redo operation is performing by the document.

onresize It triggers when the window gets resized.

onscroll It triggers when the scrollbar of an element is being scrolled.

onseeking It triggers when the seeking attribute of media element is true, and the seek

onseeked It triggers when the seeking attribute of media element is not true, and the

onselect It triggers when the element gets selected.

onstalled It triggers when there is an error in the fetching of media data.

onsubmit It triggers when the form gets submitted.

onstorage It triggers when the document loads.

onvolumechange It triggers when the media element changes its volume or when the volume
onwaiting It triggers when the media element has stopped playing, but it is expected t

onunload It triggers when a user leaves the document.

onundo It triggers when the document performs the undo operation.

ontimeupdate It triggers when the playing position of media element changes.

onsuspend It triggers when the browser is fetching the media data but stopped before t
file was fetched.

ES6 Cookies
The cookie can be defined as a small piece of text that a browser stores in the user's computer.
Cookies are an old mechanism of client-side storage that was designed to be used in server-side
scripting languages like ASP, php, etc.

Mainly, cookies are used for keeping track of information like user preferences that can retrieve for
personalizing the page when the user revisits the website. Cookies can also be created, modified, and
accessed directly by JavaScript, but the process for doing the same is somehow complicated.

Why Cookies required?


Servers and web browsers use HTTP protocol (stateless protocol) for communication. HTTP is a
stateless protocol, so after processing the initial client request by the web server, it does not remember
anything about the settings made by the client. It treats every request independently. So, the server
does not keep track of data after sending it on the browser. But in many cases, data will be required
again.

This request-response cycle between client and server is referred to as a session. Cookies are the
default mechanism that is used by the browsers for storing the data refer to the user's session.

Note: Do not save your sensitive data like your passwords and credit card information in cookies as the
malicious user could use it.

How do Cookies work?


The server sends some data to the user's browser in the form of a cookie. The browser may accept the
cookie. If it accepts, then it is stored as a record of plain text on the hard drive of the user. Now, when
a user visits another page of the same website, then the browser sends the same cookie to the server
for retrieval. Once it is retrieved, then the corresponding server remembers what was stored earlier.

Cookies are a plain-text record of data that includes five variable-length fields

o Name and value: The setting and retrieval of cookies are in the form of a key-value
o Domain: It is the domain name of the website.
o Path: It includes the webpage or directory that sets the cookie. It may be blank if you require
to retrieve the cookie from any page or directory. It's default value is the path of the current
page.
o Secure: As its name implies, the cookie may be retrieved with a secure server. If this field is
blank, then no such restrictions required.
o Expires: It is the date when the cookie will expire. If this field is blank, then the cookie will
expire when the user exits the browser.

Originally, cookies were designed for CGI (Common Gateway Interface) programming. The data in
the cookie is transmitted automatically between the web server and web browser. So, CGI scripts on
the server can read and write the values of cookies that are stored on the client-side.

In JavaScript, we can manipulate the cookies by using the cookie property of the document object. We
can also create, read, delete, and modify the cookies that apply to the current page.

Storing Cookies
The easiest way of creating or storing a new cookie is to assign a name = value string value to
the document.cookie object. It will look like this:

1. "document.cookie = "key1 = value1; key2 = value2; expires = date";

The expire attribute in the above syntax is optional. If we manually provide the valid date and time to
this attribute, then the cookie will expire on the given date and time.

The value of the cookie cannot contain whitespaces, commas, or semicolons. Because of this, we will
require to use escape() function (the built-in function of JavaScript) for encoding the values
containing these characters before storing it in the cookie. Likewise, we will also need to use
corresponding unescape() function for reading the cookie value.

1. document.cookie = "name=" + escape("XYZ");

By default, the lifetime of the above cookie is the current browser session. It means that it will be lost
when user exits the browser.

Cookies expire attribute


You can specify the cookie's lifetime by using the expires attribute. This attribute gives a way to
create a persistent cookie. Here, the declaration of time and date represents the active period of a
cookie. Once, the declared time is passed, the cookie will delete automatically.

For example:

1. document.cookie="username=XYZ;expires=Mon, 10 Aug 2040 12:00:00 UTC";

Cookies max-age attribute


To make a cookie that persists beyond the session of the current browser, we need to specify its
lifetime (in seconds). We can also specify it by using the max-age attribute. It is an alternative
to expires attribute, which specifies the expiration of cookie in seconds from the current moment. This
attribute determines the lifetime of a cookie that how long it could remain on the user's system before
deletion.
If the value of the max-age attribute is either zero or negative, then the cookie is deleted.

For example: The lifetime of the following cookie is for 30 days.

1. document.cookie="username=XYZ;max-age=" + (60*60*24*30) + ";"

Example of storing cookies


Let us try to understand the illustration for setting up the cookie by using the following example:

1. <html>
2. <head>
3. <title>Cookie Example</title>
4. </head>
5. <body style="text-align:center;">
6. <form name = "myform" action = " ">
7. Enter Name: <input type="text" name="uname" >
8. <input type="button" value="setCookie" onclick="setCookie()">
9. </form>
10. <script>
11. function setCookie()
12. {
13. if(document.myform.uname.value == ""){
14. alert("Required Name");
15. return;
16. }
17. value = escape(document.myform.uname.value) + ";";
18. document.cookie = "name = " + value;
19. document.write ("Cookie: " + "name = " + value);
20.
21. }
22.
23. </script>
24. </body>
25. </html>

Output

After the successful execution of the above code, you will get the following output.

If the textfield is empty and you are clicking on the setCookie button, then you will get an alert, as
shown in the following image.
Once you entered the required value and click on the setCookie button, then you will see the
following output.

Reading Cookies
Reading a cookie is slightly complex than setting the cookie because document.cookie property
returns you a string that contains a space and semicolon separated list of all cookies. You can use
this string where you require to access the cookie.

To get a cookie from the list, you can use the split() function of strings for breaking the string in the
form of keys and values.

Example
1. function getCookie() {
2. var cookievalue = document.cookie;
3. document.write ("Cookies : " + cookievalue );
4. }
5. // get all the pairs of cookies in an array
6. arr = cookievalue.split(';');
7.
8. // take key-value pair out of this array
9. for(var i = 0; i<arr.length; i++) // length is the array class method which returns array len
gth.
10. {
11. name = arr[i].split('=')[0];
12. value = arr[i].split('=')[1];
13. }

Updating Cookies
In JavaScript, you can change the cookie in the same way as you create it by overwriting it with a new
value. The only way to update or modify the cookie is to create another cookie. If you create a cookie
with the same name but with different path then that of an existing one, it will cause the addition of a
new cookie.

Example
1. // Creating the cookie
2. document.cookie = "name=XYZ;path=/;max-age=" + 365*24*60*60;
3.
4. // Updating the cookie
5. document.cookie = "name=ABC;path=/;max-age=" + 30*24*60*60;

Deleting a Cookie
There are some situations in which you want to delete a cookie. The process to delete a cookie is quite
simple. You do not require to specify the value of a cookie to delete it. To do this, you need to set the
value of the 'expires' attribute to a passed date.

You can see the illustration for the same in the following code:

1. document.cookie = "name=value; expires= Thu, 21 Aug 2014 16:00:00 UTC; path=/ "

ES6 Dialog boxes


There are three types of dialog boxes supported in JavaScript that are alert, confirm, and prompt.
These dialog boxes can be used to perform specific tasks such as raise an alert, to get confirmation of
an event or an input, and to get input from the user.

Let's discuss each dialog box.

Alert Dialog box


It is used to provide a warning message to users. It is one of the most widely used dialog box in
JavaScript. It has only one 'OK' button to continue and select the next task.

We can understand it by an example like suppose a textfield is mandatory to be filled out, but the user
has not given any input value to that text field, then we can display a warning message by using
the alert box.

Syntax

1. alert(message);

Example

Let us see the demonstration of an alert dialog box by using the following example.

1. <html>
2.
3. <head>
4. <script type="text/javascript">
5. function show() {
6. alert("It is an Alert dialog box");
7. }
8. </script>
9. </head>
10.
11. <body>
12. <center>
13. <h1>Hello World :) :)</h1>
14. <h2>Welcome to javaTpoint</h2>
15. <p>Click the following button </p>
16. <input type="button" value="Click Me" onclick="show();" />
17. </center>
18. </body>
19.
20. </html>

Output

After the successful execution of the above code, you will get the following output.

After clicking on the Click Me button, you will get the following output:

Confirmation Dialog box


It is widely used for taking the opinion from the user on the specific option. It includes two buttons,
which are OK and Cancel. As an example, suppose a user is required to delete some data, then the
page can confirm it by using the confirmation box that whether he/she wants to delete it or not.

If a user clicks on the OK button, then the method confirm() returns true. But if the user clicks on
the cancel button, then the confirm() method returns false.

Syntax
1. confirm(message);

Example

Let us understand the demonstration of this dialog box by using the following example.

1. <html>
2.
3. <head>
4. <script type="text/javascript">
5. function show() {
6. var con = confirm ("It is a Confirm dialog box");
7. if(con == true) {
8. document.write ("User Want to continue");
9. }
10. else {
11. document.write ("User does not want to continue");
12. }
13. }
14. </script>
15. </head>
16.
17. <body>
18. <center>
19. <h1>Hello World :) :)</h1>
20. <h2>Welcome to javaTpoint</h2>
21. <p>Click the following button </p>
22. <input type="button" value="Click Me" onclick="show();" />
23. </center>
24. </body>
25.
26. </html>

Output

After the successful execution of the above code, you will get the following output.

When you click on the given button, then you will get the following output:
After clicking the OK button, you will get:

On clicking the Cancel button, you will get:

Prompt Dialog box


The prompt dialog box is used when it is required to pop-up a text box for getting the user input. Thus,
it enables interaction with the user.

The prompt dialog box also has two buttons, which are OK and Cancel. The user needs to provide
input in the textbox and then click OK. When a user clicks on the OK button, then the dialog box reads
that value and returns it to the user. But on clicking the Cancel button, prompt() method
returns null.

Syntax

1. prompt(message, default_string);

Let us understand the prompt dialog box by using the following illustration.

Example

1. <html>
2.
3. <head>
4. <script type="text/javascript">
5. function show() {
6. var value = prompt("Enter your Name : ", "Enter your name");
7. document.write("Your Name is : " + value);
8. }
9. </script>
10. </head>
11.
12. <body>
13. <center>
14. <h1>Hello World :) :)</h1>
15. <h2>Welcome to javaTpoint</h2>
16. <p>Click the following button </p>
17. <input type="button" value="Click Me" onclick="show();" />
18. </center>
19. </body>
20.
21. </html>

Output

After executing the above code successfully, you will get the following output.

When you click on the Click Me button, you will get the following output:

Enter your name and click OK button, you will get:


ES6 Page Redirect
Redirect is nothing but a mechanism of sending search engines and users on a different URL from the
original one. The redirected page can be on the same server or on a different server. It can also be on
the same website or on different websites.

Redirect to a different page that was not requested is done by using ECMAScript 2015 or ES6. There
are several methods used for performing page redirection, such as location.href,
location.replace(), and many more.

Let us try to understand some of the methods in JavaScript that are used for page redirection.

window.location and window.location.href


window.location object is a property of the window object. There are several methods to redirect a
web page. Almost all methods are related to the window.location object.

It can be used for getting the address of the current URL or the web address.
The window.location object can be written without adding the window prefix.

Example

1. window.location = " https://www.javatpoint.com/";

location.replace()
It is one of the commonly used window.location object. It is used for replacing the original document
with a new one.

In this method, we can pass a new URL, and then it will perform an HTTP redirect.

Syntax

1. window.location.replace("new URL");

Example

1. window.location.replace("https://www.javatpoint.com/");

location.assign()
This method is used to load a new document within the browser window.

The difference between the location.assign() and location.replace() method is that


the replace() method deletes the current URL from the history of the document. So, it will not be
possible to perform back navigation. In this case, we cannot use the back button.

To avoid this, we should use the location.assign() method because it loads a new browser
document.

Syntax

1. window.location.assign("https://www.javatpoint.com/");
location.reload()
This method is used for reloading the current document dynamically. We can specify a Boolean
parameter, either true or false. It the parameter value is true, then the method will force the browser
to reload the page from the server. But if it is false or unspecified, then the browser may reload the
page from the cache.

Example

1. window.location.reload("https://www.javatpoint.com/");

window.navigate()
This method is only available in Internet explorer because all the other browsers remove this method.
It is similar to assigning a new value to the window.location.href property.

Example

1. window.navigate("https://www.javatpoint.com/");

Search Engine Optimization and page redirecting


Generally, search engines do not analyze the JavaScript to check the redirection. So, if it is required to
notify the search engines (SEO) about the URL forwarding, we need to add the rel = "canonical" tag
within the head section of the web page.

Example

1. <link rel = "canonical" href = "https://www.javatpoint.com/" />

ES6 Numbers
ES6 Number has several methods and properties to perform numeric functions that has the date,
floating points, integers, etc. Using Numbers in ES6, we can easily work with the Number objects. It is
because the browser automatically converts number literals to instances of the number class.

The Number object is created by using the Number() constructor. Some of the primary uses of the
Number object include NaN, which will return when the argument cannot be converted into a number.

Syntax
1. var num = new Number(value);

Parameter
Value: It is the numeric value of the object being created. If we give any non-number argument in
place of it, then it returns NaN because the corresponding argument cannot be converted into a
number.

Number Properties
Let us see some of the properties of Number object which are introduced in ES6 are tabulated as
follows:

S.no Properties Description

1. Number.EPSILON It defines the smallest intervals between two represen

2. Number.MAX_SAFE_INTEGER It defines maximum safe integer in JavaScript (253-1)

3. Number.MAX_VALUE It defines the largest possible representable number.

4. Number.MIN_SAFE_INTEGER It defines the minimum safe integer in JavaScript (-(25

5. Number.MIN_VALUE It defines the smallest positive number, which is closes

6. Number.Nan It defines 'not a number' value.

7. Number.NEGATIVE_INFINITY It defines a value, which is less than the defined numb

8. Number.POSITIVE_INFINITY It defines a value, which is greater than the defined nu

9. Number.prototype It defines a special value that represents infinity.

Let us try to elaborate on the Number properties introduced in ES6.

EPSILON
This property represents the difference between 1 and the smallest floating-point number, which is
greater than 1. We do not have to create a Number object for accessing the static property because
we can simply use Number.EPSILON property.

Example

1. var value = Number.EPSILON;


2. console.log(value);

Output

2.220446049250313e-16

Number.MAX_SAFE_INTEGER
This property represents the maximum safe integer in JavaScript (253-1).

Example
1. var value = Number.MAX_SAFE_INTEGER;
2. console.log(value);

Output

9007199254740991

Number.MAX_VALUE
This property belongs to the static Number object and represents constants for the largest possible
positive numbers.

Example

1. var val = Number.MAX_VALUE;


2. console.log("Number.MAX_VALUE equals to: " + val );

Output

Number.MAX_VALUE equals to: 1.7976931348623157e+308

Number.MIN_SAFE_INTEGER
It represents the minimum safe integer in JavaScript (-(253-1)).

Example

1. var val = Number.MIN_SAFE_INTEGER;


2. console.log("Number. MIN_SAFE_INTEGER equals to: " + val );

Output

Number. MIN_SAFE_INTEGER equals to: -9007199254740991

Number.MIN_VALUE
It represents the smallest positive numeric value.

Example

1. var val = Number.MIN_VALUE;


2. console.log("Number.MIN_VALUE equals to : " + val );

Output

Number.MIN_VALUE equals to : 5e-324

Number Methods
The Number object contains only default methods that are part of every object's definition. The
methods of the number object are tabulated as follows:
S.no. Methods Description

1. Number.isNan() It returns whether the passed value is NaN or not.

2. Number.isFinite() It returns whether the passed value is a finite number.

3. Number.isInteger() It returns whether the passed value is an integer.

4. Number.isSafeInteger() It determines whether the passed value is a safe integer (range be


1) and (253-1)).

5. Number.parseFloat() It is equivalent to the parseFloat() of the global object.

6. Numbr.pareInt() It is equivalent to the parseInt() of the global object.

Let us try to elaborate on the above Number methods introduced in ES6.

Number.isNan()
It determines whether the value is Nan or not. It returns true if the value is not a number.

Example

1. var res = Number.isNaN(NaN);


2. console.log(res);
3.
4. var res1 = Number.isNaN('Nan');
5. console.log(res1);
6.
7. var res2 = Number.isNaN(123);
8. console.log(res2);

Output

true
false
false

Number.isFinite()
It determines whether a value is a finite number or not. It returns true if the value is of the Number
type and equates to a finite number. Otherwise, it returns false.

Example

1. var res = Number.isFinite(Infinity);


2. console.log(res);
3.
4. var res1 = Number.isFinite(123);
5. console.log(res1);
6.
7. var res2 = Number.isFinite('Infinity');
8. console.log(res2);

Output

false
true
false

Number.isInteger()
As its name implies, it determines whether the passed value is an integer or not. It returns true if the
value is a number and must be an integer (number without decimals). Otherwise, it returns false.

Example

1. var res = Number.isInteger(-100);


2. console.log(res);
3.
4. var res1 = Number.isInteger(100);
5. console.log(res1);
6.
7. var res2 = Number.isInteger(1.001);
8. console.log(res2);

Output

true
true
false

Number.isSafeInteger()
A safe integer is an integer which is in the range of - (253 - 1) and (253-1). The
Number.isSafeInteger() method determines whether or not the value is a safe integer.

Example

1. var res = Number.isSafeInteger(-100);


2. console.log(res);
3.
4. var res1 = Number.isSafeInteger(100.9);
5. console.log(res1);
6.
7. var res2 = Number.isSafeInteger(-100);
8. console.log(res2);
9.
10. var res3 = Number.isSafeInteger(Math.pow(2,53));
11. console.log(res3);

Output

true
false
true
true

Binary, Octal and Hexadecimal Literals


ES6 added support for binary literals and changed the way of representing the literals. Let's see the
representation of the literals in ES6.

Binary Literals representation


Binary literals in ES6 are represented by using the 0b prefix, followed by the sequence of binary
numbers, which are 0 and 1.

The prefix can be written in lowercase as well as in uppercase. However, the lowercase is
recommended for the prefix.

Example

1. console.log(0b010)
2. console.log(0b110)
3. console.log(0b101)
4. console.log(0B100)

Output

2
6
5
4

Octal Literals representation


Octal literals in ES6 are represented by using the 0o prefix, followed by the sequence of octal digits
(from 0 to 7). We cannot include a digit or the combination of digits in octal literal that is out of range
(0 to 7).

Example

1. console.log(0o34)
2. console.log(0o1007)
3. console.log(0o571234)

Output

28
519
193180
Hexadecimal Literals representation
Hexadecimal literals in ES6 are represented by using the 0x prefix

Example

1. console.log(0x678)
2. console.log(0x100)
3. console.log(0x788)

Output

1656
256
1928

ES6 Boolean
The ES6 Boolean objects can represent two values, either 'true' or 'false'. In JavaScript, the Boolean
is used as a function to get the value of an object, a variable, conditions, expressions, and many more
in terms of true and false.

The object has the initial false value if the value parameter is omitted or 0, negative, false, null, NaN,
undefined, or an empty ("") string.

Syntax

1. var val = new Boolean(value);

There are three methods and two properties of the Boolean object. Let us try to understand the
properties and methods of the Boolean object.

Boolean Properties
There are two properties of the Boolean object that are tabulated as follows:

S.no. Properties Description

1. Constructor This property returns a constructor function for an object.

2. Prototype It is used to add properties and methods to the Boolean instances.

Let us try to elaborate on the above Boolean properties.

ES6 Boolean constructor() property


The JavaScript Boolean constructor() method is used to return the reference to the Boolean function
that created the Boolean prototype.
Syntax

1. Boolean.constructor

Return value

1. Boolean() { [native code] }.

Example

1. var example = new Boolean( );


2. console.log("example.constructor() is : " + example.constructor);

Output

example.constructor() is : function Boolean() { [native code] }

ES6 Boolean prototype property


It is an inbuilt property in ES6, which is used for adding new properties and methods to any Boolean
instance such as Number, String, Date, etc. It is a global property which is available with almost all
objects.

Syntax

1. Boolean.prototype.name = value

Return value

o Boolean.prototype.valueOf(): It is used to return the value of Boolean object.


o Boolean.prototype.toString(): It is used to return a string according to the Boolean value.

Example

1. Boolean.prototype.color = function() {
2. if (this.valueOf() == true) {
3. return "Yellow";
4. }
5. else {
6. return "Orange";
7. }
8. };
9.
10. function show() {
11. var my_color = true;
12. console.log(my_color.color());
13. }
14. show();

Output
Yellow

Boolean Methods
The Boolean object contains three methods, which are tabulated as follows:

S.no. Methods Description

1. toSource() This method returns a string having a source of the Boolean object.

2. toString() It returns a string of either true or false depends on the Boolean object va

3. valueOf() It returns the primitive value of the Boolean object.

Let us try to elaborate on the above Boolean methods.

Boolean.prototype.toSource() method
This method returns a string that contains the source code of the Boolean object. It overrides
the Object.prototype.toSource() method.

Note: This method is not compatible with all browsers.

Syntax

1. boolean.toSource();

Example

1. <script>
2. var obj = new Boolean(true);
3. document.write(obj.toSource());
4. </script>

You can run the above example in the Firefox browser because this method is not compatible with
other browsers.

Boolean.prototype.toString() method
It returns a string of either true or false depends on the Boolean object value.

Syntax

1. Boolean.toString()

Example
1. var obj = new Boolean(true);
2. console.log(obj.toString());

Output

true

Boolean.prototype.valueOf() method
It returns the primitive value of the Boolean object.

Syntax

1. boolean.valueOf()

Example

1. var obj = new Boolean(true);


2. console.log(obj.valueOf());

Output

true

ES6 void Keyword


The void keyword is used as the return type of functions that do not return any value. It evaluates the
given expression and returns undefined. It is an important JavaScript keyword that might be used as
a unary operator and appears before the single operand of any type.

It specifies an expression to evaluate without returning any value. The void operator is often used for
obtaining the undefined primitive value.

Syntax

1. void expression

Example

1. var x,y,z;
2. x = void ( y = 50, z = 70 );
3. console.log('x = ' + x + ' y = ' + y +' z = ' + z );

Output

x = undefined y = 50 z = 70

Immediately Invoked function expressions (IIFE) and void


keyword
Using an IIFE, the void can be used for forcing the function keyword to be treated as an expression
rather than a declaration.

Example

1. void function hello() {


2. var msg = function ()
3. {console.log("Welcome back!!")};
4. msg();
5. }();

Output

Welcome back!!

JavaScript URI and void keyword


When a browser follows the URI, it evaluates the URI code and replaces the page content with the
returned value unless the value is undefined. The JavaScript: URI has widely used syntax in an
HTML page.

The void operator can be used to return the undefined value.

Let us understand the illustration for the same.

Example

In the following example, we are defining two links that have alert boxes. In one link, we are using the
void keyword. When the corresponding link gets clicked, then it evaluates the JavaScript alert and
passes it to the void() operator. The void() operator will return an undefined value. Hence the alert
function will not display on the page.

When you click on the second link, then it will display an alert dialog box.

1. html>
2.
3. <head>
4. </head>
5. <body>
6. <center>
7. <h1>Hello World :) :)</h1>
8. <h2>Welcome to javaTpoint</h2>
9. <h2>Click the following links to see the changes</h2>
10. <a href = "javascript:void(javascript:alert('hello world!!'))">
11. It will do nothing.
12. </a>
13. <br/><br/>
14. <a href = "javascript:alert('Welcome to javaTpoint');">Click here for an alert</a>
15. </center>
16. </body>
17.
18. </html>
Output

After the successful execution of the above code, you will get the following output:

When you click on the first link, you will get nothing. But, on clicking the second link, you will get the
following screen:

ES6 Page Printing


In several cases, it is required to place a button on a webpage that prints the content of the webpage
by using the actual printer. JavaScript helps us in the implementation of printing a web page.

When the print function window.print() in JavaScript gets executed, then it prints the current
webpage. We can directly call this function simply by using it in the onclick event.

Syntax

1. window.print();

Example

1. <html>
2.
3. <head>
4.
5. </head>
6.
7. <body>
8. <center>
9. <h1>Hello World :) :)</h1>
10. <h2>Welcome to javaTpoint</h2>
11. <h2>Click the following print button to see the changes</h2>
12. <input type = "button" value = "Print" onclick = "window.print()"/>
13. </center>
14. </body>
15.
16. </html>

Output

After the successful execution of the above code, you will get the following output:

When you click on the Print button, you will get the following screen:
ES6 Modules
Modules are the piece or chunk of a JavaScript code written in a file. JavaScript modules help us to
modularize the code simply by partitioning the entire code into modules that can be imported from
anywhere. Modules make it easy to maintain the code, debug the code, and reuse the piece of code.
Each module is a piece of code that gets executed once it is loaded.

Modules in ES6 is an essential concept. Although it is not available everywhere, but today we can use it
and can transpile into ES5 code. Transpilation is the process of converting the code from one language
into its equivalent language. The ES6 module transpiler tool is responsible for taking the ES6 module
and converts it into a compatible code of ES5 in the AMD (Asynchronous module definition is a
specification for the JavaScript programming language) or in the CommonJS style.

During the build process, we can use Gulp, Babel, Grunt, or other transpilers for compiling the
modules. The variables and functions in a module are not available for use unless the file exports them.

Exporting and Importing a Module


Exporting a Module
JavaScript allows us to export a function, objects, classes, and primitive values by using
the export keyword. There are two kinds of exports:

o Named Exports: The exports that are distinguished with their names are called as named
exports. We can export multiple variables and functions by using the named export.
o Default Exports: There can be, at most, one value that can be exported by using the default
export.

Importing a Module
To import a module, we need to use the import keyword. The values which are exported from the
module can be imported by using the import keyword. We can import the exported variables,
functions, and classes in another module. To import a module, we simply have to specify their path.

When you import the named export, you must have to use the same name as the corresponding
object. When you import the default export, we can use any name of the corresponding object.

Let us elaborate on these exports and imports.

Named Exports and Imports


Named exports are distinguished with their names. The class, variable, or any function which is
exported by using the named export can only be imported by using the same name.

Multiple variables and functions can be imported and exported by using the named export.

Syntax

Let us see the syntax to use named export in class, function, or in a variable. Below we are showing
how to individually export the class, variable, and function by using the named export.

1. //Named export in class


2. class Nokia{
3. //properties
4. //methods
5. }
6. export {Nokia}; //Named export
7.
8. //Named export in functions
9. function show(){
10. }
11. export {show};
12.
13. //Named export in Variables
14. const a = 10;
15. export {a};

We can apply more than one named export in a module. We can use the syntax of
multiple named exports in a module as follows:

Mobile.js

1. class Nokia{
2. //properties
3. //methods
4. }
5. function show(){
6. }
7. const a = 10;
8. export {Nokia, show};

Let us see how to import the named exports.

Importing the Named export


To import the bindings that are exported by another module, we have to use the
static import statement. The imported modules are always in the strict mode, whether we declare
them in strict mode or not.

Syntax

App.js

1. import {Nokia, show} from './Mobile.js';

Importing all

If we want to import all of the export statements simultaneously, then we can import them individually.

But it will be hard when we have so many named exports. So, to make it easier, we can do it as
follows:

1. import * as device from './Mobile.js'; // Here, the device is an alias, and Mobile.js is the module na
me.
Suppose, we have defined a class Nokia in the module Mobile.js, and if we want to use it then by
using the alias, we can perform it as:

1. device.Nokia //if we have a class Nokia


2. device.show // if we have a function show
3. device.a // if we have a variable a

Let us try to understand the Named export and import within a single example.

We have to make two JavaScript modules to perform export and import. In the first module, we export
the class, function, and variable. In the second module, we will import them by using
the named import.

Example - Named Export and Import


Here, we are creating two JavaScript modules in which the first JavaScript module is Mobile.js, and
the second module name is App.js. We are also creating an HTML file Example.html. Then, we will
execute this .html file in the server.

Next, we have to manually link the JavaScript file in the HTML file by using the src attribute in
the <script></script> tag. But the module still will not work. To enable the module, we have to use
the type = "module" in the <script></script> tag.

Example.html

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
7. <script type = "module" src = "App.js"></script>
8. <title>Document</title>
9. </head>
10. <body>
11. <h1>ES6 Modules import and export</h1>
12. </body>
13. </html>

Mobile.js

1. class Display{
2. show(){
3. console.log("Hello World :)");
4. }
5. }
6. function javaT(){
7. console.log("Welcome to javaTpoint");
8. }
9. export {Display,javaT};

App.js
1. import {Display,javaT} from "./Mobile.js";
2. const d = new Display();
3. d.show();
4. javaT();

Output

Run the above Example.html file in the live server. Then, open the terminal in the browser by
using ctrl+shift+I. After the successful execution, you will get the following output:

Default Exports and Imports


We can have only one default export in a module. A default export can be imported with any name.

Syntax

Let us see the syntax to use default export in class, function, or in a variable. Below we are showing
how to individually export the class, variable, and function by using the default export.

Unlike the named export, we cannot simultaneously make more than one export statement
in default export.

1. //Default export in class


2. class Nokia{
3. //properties
4. //methods
5. }
6. export default Nokia; //Default export
7.
8. //Deafult export in functions
9. function show(){
10. }
11. export default show;
12.
13. //Default export in Variables
14. const a = 10;
15. export default a;

Importing the Default export


To import the bindings that are exported by another module, we have to use the
static import statement. The imported modules are always in the strict mode, whether we declare
them in strict mode or not.

Syntax
Mobile.js

1. class Nokia{
2. //properties
3. //methods
4. }
5. export default Nokia;

App.js

1. import Nokia from './Mobile.js';

Example - Default import and export


Example.html

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
7. <script type = "module" src = "App.js"></script>
8. <title>Document</title>
9. </head>
10. <body>
11. <h1>ES6 Modules import and export</h1>
12. <h2>Default import and export</h2>
13. </body>
14. </html>

Mobile.js

1. class Display{
2. show(){
3. console.log("Hello World :)");
4. console.log("Default Import and Export Example");
5. }
6. }
7. export default Display;

App.js

1. import Display from "./Mobile.js";


2. const d = new Display();
3. d.show();

Output
Run the above Example.html file in the live server. Then, open the terminal in the browser by
using ctrl+shift+I. After the successful execution, you will get the following output:

ES6 Cyclic dependencies


Cyclic dependency is a direct or indirect relation between two or more modules that depend on each
other. Such modules are known as the mutually recursive modules.

The modules in ES6 automatically supports the cyclic dependencies. Two modules, such as A and B,
are cyclically dependent on each other if both A imports B and B imports A either transitively or
indirectly.

Suppose we have three modules named A, B, and C. Their chain of dependencies is like A->B->C->A,
i.e., A is dependent upon B; B is dependent upon C and C is dependent upon A.

CommonJS and some of the other libraries support the circular dependencies, but there is a problem
with importing and using named exports from a circular dependent module.

ES6 solves this problem by sharing the bindings to the values rather than the values itself in the
exports. It means the connection with the variables declared in the body of the module can be done.
We can see the demonstration for the same in the following code:

Example
Example.html

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
7. <script type = "module" src = "App.js"></script>
8. <title>Document</title>
9. </head>
10. <body>
11. <h1>ES6 Cyclic dependencies</h1>
12. </body>
13. </html>

Mobile.js

1. export let count = 0;


2. export function show() {
3. count++;
4. }
App.js

1. import { show, count } from './Mobile.js';


2. console.log(count);
3. show();
4. console.log(count);

Output

ES6 Promises
A Promise represents something that is eventually fulfilled. A Promise can either be rejected or
resolved based on the operation outcome.

ES6 Promise is the easiest way to work with asynchronous programming in JavaScript. Asynchronous
programming includes the running of processes individually from the main thread and notifies the main
thread when it gets complete. Prior to the Promises, Callbacks were used to perform asynchronous
programming.

Callback
A Callback is a way to handle the function execution after the completion of the execution of another
function.

A Callback would be helpful in working with events. In Callback, a function can be passed as a
parameter to another function.

Why Promise required?


A Callback is a great way when dealing with basic cases like minimal asynchronous operations. But
when you are developing a web application that has a lot of code, then working with Callback will be
messy. This excessive Callback nesting is often referred to as Callback hell.

To deal with such cases, we have to use Promises instead of Callbacks.

How Does Promise work?


The Promise represents the completion of an asynchronous operation. It returns a single value
based on the operation being rejected or resolved. There are mainly three stages of the Promise,
which are shown below:
Pending - It is the initial state of each Promise. It represents that the result has not been computed
yet.

Fulfilled - It means that the operation has completed.

Rejected - It represents a failure that occurs during computation.

Once a Promise is fulfilled or rejected, it will be immutable. The Promise() constructor takes two
arguments that are rejected function and a resolve function. Based on the asynchronous operation, it
returns either the first argument or second argument.

Creating a Promise
In JavaScript, we can create a Promise by using the Promise() constructor.

Syntax

1. const Promise = new Promise((resolve,reject) => {....});

Example

1. let Promise = new Promise((resolve, reject)=>{


2. let a = 3;
3. if(a==3){
4. resolve('Success');
5. }
6. else{
7. reject('Failed');
8. }
9. })
10. Promise.then((message)=>{
11. console.log("It is then block. The message is: ?+ message)
12. }).catch((message)=>{
13. console.log("It is Catch block. The message is: ?+ message)
14. })

Output

It is then block. The message is: Success

Promise Methods
The Promise methods are used to handle the rejection or resolution of the Promise object. Let's
understand the brief description of Promise methods.

.then()
This method invokes when a Promise is either fulfilled or rejected. This method can be chained for
handling the rejection or fulfillment of the Promise. It takes two functional arguments
for resolved and rejected. The first one gets invoked when the Promise is fulfilled, and the second
one (which is optional) gets invoked when the Promise is rejected.

Let's understand with the following example how to handle the Promise rejection and resolution by
using .then() method.

Example

1. let success = (a) => {


2. console.log(a + " it worked!")
3. }
4.
5. let error = (a) => {
6. console.log(a + " it failed!")
7. }
8.
9. const Promise = num => {
10. return new Promise((resolve,reject) => {
11. if((num%2)==0){
12. resolve("Success!")
13. }
14. reject("Failure!")
15. })
16. }
17.
18. Promise(100).then(success, error)
19. Promise(21).then(success,error)

Output

Success! it worked!
Failure! it failed!

.catch()
It is a great way to handle failures and rejections. It takes only one functional argument for handling
the errors.
Let's understand with the following example how to handle the Promise rejection and failure by
using .catch() method.

Example

1. const Promise = num => {


2. return new Promise((resolve,reject) => {
3. if(num > 0){
4. resolve("Success!")
5. }
6. reject("Failure!")
7. })
8. }
9.
10. Promise(20).then(res => {
11. throw new Error();
12. console.log(res + " success!")
13. }).catch(error => {
14. console.log(error + " oh no, it failed!")
15. })

Output

Error oh no, it failed!

.resolve()
It returns a new Promise object, which is resolved with the given value. If the value has
a .then() method, then the returned Promise will follow that .then() method adopts its eventual
state; otherwise, the returned Promise will be fulfilled with value.

1. Promise.resolve('Success').then(function(val) {
2. console.log(val);
3. }, function(val) {
4. });

.reject()
It returns a rejected Promise object with the given value.

Example

1. function resolved(result) {
2. console.log('Resolved');
3. }
4.
5. function rejected(result) {
6. console.error(result);
7. }
8.
9. Promise.reject(new Error('fail')).then(resolved, rejected);

Output

Error: fail

.all()
It takes an array of Promises as an argument. This method returns a resolved Promise that fulfills
when all of the Promises which are passed as an iterable have been fulfilled.

Example

1. const PromiseA = Promise.resolve('Hello');


2. const PromiseB = 'World';
3. const PromiseC = new Promise(function(resolve, reject) {
4. setTimeout(resolve, 100, 1000);
5. });
6.
7. Promise.all([PromiseA, PromiseB, PromiseC]).then(function(values) {
8. console.log(values);
9. });

Output

[ 'Hello', 'World', 1000 ]

.race()
This method is used to return a resolved Promise based on the first referenced Promise that resolves.

Example

1. const Promise1 = new Promise((resolve,reject) => {


2. setTimeout(resolve("Promise 1 is first"),1000)
3. })
4.
5. const Promise2= new Promise((resolve,reject) =>{
6. setTimeout(resolve("Promise 2 is first"),2000)
7. })
8.
9. Promise.race([Promise1,Promise2]).then(result => {
10. console.log(result);
11. })

Output

Promise 1 is first

ES6 Promise Chaining


Promise chaining allows us to control the flow of JavaScript asynchronous operations. By using Promise
chaining, we can use the returned value of a Promise as the input to another asynchronous operation.

Sometimes, it is desirable to chain Promises together. For example, suppose we have several
asynchronous operations to be performed. When one operation gives us data, we will start doing
another operation on that piece of data and so on.

Promise chaining is helpful when we have multiple interdependent asynchronous functions, and each of
these functions should run one after another.

Let us try to understand the concept of Promise chaining by using the following example:

Example

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
7.
8. <title>Document</title>
9. </head>
10. <body>
11. <script>
12. const PromiseA = () =>{
13. return new Promise((resolve,reject)=>{
14. resolve("Hello Promoise A");
15. });
16. }
17.
18. const PromiseB = () =>{
19. return new Promise((resolve,reject)=>{
20. resolve("Hello Promise B");
21. });
22. }
23.
24.
25. const PromiseC = () =>{
26. return new Promise((resolve,reject)=>{
27. resolve("Hello Promise C");
28. });
29. }
30. PromiseA().then((A)=>{
31. console.log(A);
32. return PromiseB();
33. }).then((B)=>{
34. console.log(B);
35. return PromiseC();
36. }).then((C)=>{
37. console.log(C);
38. });
39. </script>
40. </body>
41. </html>

Execute the above code in the browser and open the terminal by using ctrl+shift+I. After the
successful execution of the above code, we will get the following output.

Output

ES6 Validations
Validation is the process of checking whether the information provided by the front-end user is correct
or not as per the requirements. If the data provided by the client was incorrect or missing, then the
server will have to send that data back to the client and request for resubmitting the form with the
correct information.

Generally, the validation process is done at the server-side, which sends that validation information to
the front-end user. This process wastes the execution time and user time.

JavaScript gives us a way to validate the form's data before sending it to the server-side. Validation in
forms generally performs two functions, which are as follows:

o Basic validation- It is a process to make sure that all of the mandatory fields are filled or not.
o Data Format validation- As its name implies, it is the process to check that entered data is
correct or not. We have to include appropriate logic for testing the correctness of data.

Let us try to elaborate on the basic form validation and data format validation.

Basic Form Validation


It validates the mandatory input fields of the form, whether the required fields are filled or not.

Let us understand the process of basic form validation by using the following example.

Example

1. <!DOCTYPE html>
2. <html>
3.
4. <head>
5. <title>Example of Basic form Validation</title>
6. <script>
7. function validateBasic() {
8. var name1 = document.basic.name.value;
9. var qual1 = document.basic.qual.value;
10. var phone1 = document.basic.phone.value;
11.
12. if (name1 == "") {
13. alert("Name required");
14. return false;
15. }
16.
17. if (qual1 == "") {
18. alert("Qualification required");
19. return false;
20. }
21.
22. if (phone1 == "") {
23. alert("Mobile number is required");
24. return false;
25. }
26.
27. }
28. </script>
29. </head>
30.
31. <body>
32. <center>
33. <h1>Basic Form Validation</h1>
34. <form name="basic" action="#" onsubmit="return validateBasic()">
35. <table cellspacing = "2" cellpadding = "2" border = "1">
36. <tr>
37. <td>Name: </td>
38. <td><input type="text" name="name"></td>
39. <tr>
40. <tr>
41. <td> Qualification: </td>
42. <td><input type="text" name="qual"></td>
43. </tr>
44. <tr>
45. <td>Phone no.:</td>
46. <td><input type="text" name="phone"></td>
47. </tr>
48. </table>
49. <input type="submit" value="Submit">
50. </form>
51. <p id="d1"></p>
52. </center>
53. </body>
54.
55. </html>

Output

Data Format Validation


In data format validation, there is the checking of the entered data for the correct value. It validates
already filled input fields that whether the filled information is correct or not.

Let's understand the concept of data format validation with the following example.

Example

1. <!DOCTYPE html>
2. <html>
3.
4. <head>
5. <title>Example of Basic form Validation</title>
6. <script>
7. function validateBasic() {
8. var name1 = document.basic.name.value;
9. var qual1 = document.basic.qual.value;
10. var phone1 = document.basic.phone.value;
11. var id = document.basic.em.value;
12.
13. if (name1 == "") {
14. alert("Name required");
15. return false;
16. }
17. if(name1.length<5){
18. alert("Username should be atleast 5 characters");
19. return false;
20. }
21.
22. at = id.indexOf("@");
23. dot = id.lastIndexOf(".");
24.
25. if (at < 1 || ( dot - at < 2 )) {
26. alert("Incorrect Email-ID")
27. return false;
28. }
29.
30. if (qual1 == "") {
31. alert("Qualification required");
32. return false;
33. }
34.
35. if (phone1 == "") {
36. alert("Mobile number is required");
37. return false;
38. }
39. if(phone1.length<10 || phone1.length>10){
40. alert("Mobile number should be of 10 digits");
41. return false;
42. }
43.
44. }
45. </script>
46. </head>
47.
48. <body>
49. <center>
50. <h1>Basic Form Validation</h1>
51. <form name="basic" action="#" onsubmit="return validateBasic()">
52. <table cellspacing = "2" cellpadding = "2" border = "1">
53. <tr>
54. <td>Name: </td>
55. <td><input type="text" name="name"></td>
56. </tr>
57. <tr>
58. <td>Email: </td>
59. <td><input type="email" name="em"></td>
60. </tr>
61.
62. <tr>
63. <td> Qualification: </td>
64. <td><input type="text" name="qual"></td>
65. </tr>
66. <tr>
67. <td>Phone no.:</td>
68. <td><input type="number" name="phone"></td>
69. </tr>
70. </table>
71. <input type="submit" value="Submit">
72. </form>
73. <p id="d1"></p>
74. </center>
75. </body>
76.
77. </html>

Output

ES6 Animation
Animations in JavaScript can handle the things that CSS can't. Several elements in JavaScript help to
create a complex animation such as Fade effect, Fireworks, Roll-in or Roll-out, etc. By using
JavaScript, we can move the DOM elements such as </img>, </div> or any other HTML element.

There are two ways to perform animation in JavaScript, which are as follows:

o Using the setInterval() method: It takes two arguments that are a function and an integer.
This method terminates by using the clearInterval() method.
o Using the requestAnimationFrame() method: This method runs the function when the
screen is ready to accept the next repaint. It takes a single argument function. The animated
effect occurs when we recursively call this method. The expected animation is created frame by
frame, and every frame is called when the browser is ready for it.

Let us try to elaborate on these methods.

setInterval() method
It is the traditional method of JavaScript for producing animation effects. It relies on the repeated
execution of code for making changes in the element frame by frame.

1. anime = setInterval(show, t);


2. //It calls the function show after every t milliseconds
3. clearInterval(anime);
4. //It terminates above process

If the function show produces a change in element style, then setInterval(show, t) method can be
used for producing gradual changes in the style of an element after every time interval. When the time
interval is small, then the animation looks continuous.

requestAnimationFrame() method
This method is easy to set up and hard to cancel. It is optimized to perform smooth animation. The
loops in it are needed to be created manually, and also the timing needs to be set up manually. This
method is not made to be used at specific intervals.

This method is designed to loop at 60fps (frames per second) to perform smooth animation. It won't
run in the background, and it is also energy efficient.

Now, let's see some of the demonstrations of JavaScript Animation.


Example-1

In this example, we are implementing a simple animation by using the properties of the DOM object
and functions of JavaScript. We use the JavaScript function getElementById() for getting the DOM
object and then assign that object into a global variable.

Let's understand the simple animation by using the following example.

Example

1. <html>
2. <head>
3. <script type = "text/javascript">
4.
5. var img = null;
6. function init(){
7. img = document.getElementById('myimg');
8. img.style.position = 'relative';
9. img.style.left = '50px';
10. }
11. function moveRight(){
12. img.style.left = parseInt(
13. img.style.left) + 100 + 'px';
14. }
15. window.onload = init;
16.
17. </script>
18. </head>
19.
20. <body>
21. <form>
22. <img id = "myimg" src = "train1.png" />
23. <center>
24. <p>Click the below button to move the image right</p>
25. <input type = "button" value = "Click Me" onclick = "moveRight();" />
26. </center>
27. </form>
28. </body>
29.
30. </html>

Output

LIVE OUTPUT

Example-2

Let's understand another example of JavaScript animation.


In this animation, we will use the setTimeout() function of JavaScript. It is obvious that if we are
using a setTimeout() function, then to clear the timer, we have to set clearTimeout() function of
JavaScript manually.

In the above example, we saw how the image moves towards right on every click. Let us try to
automate this process with the setTimeout() function of JavaScript.

1. <html>
2. <head>
3. <title>JavaScript Animation</title>
4. <script type = "text/javascript">
5. var anime ;
6. function init(){
7. img = document.getElementById('myimg');
8. img.style.position = 'relative';
9. img.style.left = '0px';
10. }
11. function towardRight(){
12. img.style.left = parseInt(img.style.left) + 10 + 'px';
13. anime = setTimeout(towardRight,50);
14. }
15. function stop() {
16. clearTimeout(anime);
17. img.style.left = '0px';
18. }
19. window.onload = init;
20. </script>
21. </head>
22.
23. <body>
24. <form>
25. <img id = "myimg" src = "train1.png" />
26. <center>
27. <h2 style="color:darkblue;">Click the following buttons to handle animation</h2>
28. <input type="button" value="Start" onclick = "towardRight();" />
29. <input type = "button" value="Stop" onclick = "stop();" />
30. <center>
31. </form>
32. </body>
33. </html>

Output

LIVE OUTPUT

Image Rollover with a mouse event


Let's understand another example of animation in which there is an image rollover by a mouse event.
When the mouse moves over the image, the HTTP image will change to the second one from the first
image. But when the mouse gets moved away from the image, then the original image will be
displayed.

Example

The onMouseOver event handler triggers when the user will move the mouse onto the link, and
the onMouseOut event handler gets trigger when the user will move the mouse away from the link.

1. <html>
2.
3. <head>
4.
5. <script type = "text/javascript">
6.
7. if(document.images) {
8. var img1 = new Image();
9. img1.src = "cat.jpg";
10. var img2 = new Image();
11. img2.src = "tiger.jpg";
12. }
13.
14. </script>
15. </head>
16.
17. <body>
18. <center>
19.
20. <a href = "#" onMouseOver = "document.myImg.src = img2.src;"
21. onMouseOut = "document.myImg.src = img1.src;">
22. <img name = "myImg" src = "cat.jpg" />
23. </a><br><br><br>
24. <h1>Move your mouse over the image to see the result</h1>
25. </center>
26. </body>
27. </html>

Output

LIVE OUTPUT

You might also like