Professional Documents
Culture Documents
Es6 PDF
Es6 PDF
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.
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).
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:
For example:
1. console.log("hello world")
2. console.log("Welcome to javaTpoint.com"); console.log("You are learning the ES6 tutorial");
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.
1. node Example.js
After the successful execution, you will get the following output:
1. Hello World
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.
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.
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.
Example
Output
Concatenating arrays
Spread operator can also be used to concatenate two or more arrays.
Example
Output
[ 'Red', 'Yellow', 'Violet', 'Orange', 'Green' ]
Copying an array
We can also copy the instance of an array by using the spread operator.
Example
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.
Example
Output
Output
Example
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
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. };
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.
By using the rest parameter, we can put all the remaining elements of an array in a new array.
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:
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 $example1=value
2. var example1=value
3. var _example$=value
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).
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:
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:
For example:
1. const y=100
2. y=200 // It will result in an error
Output:
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:
In this example, there are two variables one is outside the function (global scope), and the other is in
the function (local scope).
Output:
For example:
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
Output:
10
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
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.
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.
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…of loop Unlike object literals, it iterates the iterables (arrays, string, etc.).
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.
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
Syntax
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
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
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.
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 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
720
If you perform this example by using the while loop, then this will be written as:
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.
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.
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.
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
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
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.
1. labelname:
2. 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
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
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
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 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.
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.
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 result of the next() method is always an object having two properties:
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
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.
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
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.
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
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
Example
Output
Hello World
I am an anonymous function
Example
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
Output
Sum: 300
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.
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:
Output
140
o Optional braces for single statement and the empty braces if there is not any
parameter required.
Hello World
For example
Output
For example
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
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:
Output
100 200,300,400,500,600,700,800
For example
Output
Hello World
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
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.
Output
undefined
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.
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.
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
It is less efficient than declaring a function using a function expression or function statement.
Syntax
Parameters used
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
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
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.
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
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
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.
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:
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:
The following example will show you the illustration for the same:
Output
0
5
10
15
20
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
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]];
1. var array_name[initial_array_index][referenced_array_index]
Example
Output
2
3
4
4
9
16
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
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.
7. Array.prototype.keys() It returns an array iterator object along with the keys of the
array.
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
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
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
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.
Note: Instead of adding more items to the array, this method only overwrites the elements of the
original array.
Syntax
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
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
arr: It is also an optional parameter. It is the array on which the find() operated.
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
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.
Output
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
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
Output
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
Parameter Values
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
Output
1. concat() This method returns a new array object which contains two or more
merged arrays.
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.
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.
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.
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
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:
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.
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' ]
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
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:
ES6 makes the object literal more concise and robust by extending the syntax in different ways.
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
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
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.
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
In ES6
Output
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. };
o Object.assign() method
o Object spread syntax method
Syntax
1. Object.assign(target, sources)
Example
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.
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
Syntax
Example
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
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.
Output
100
200
Output
Arun
First
24
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
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
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
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:
The Map () accepts an optional iterable object, whose elements are in the key-value pairs.
Map Properties
1. Map.prototype.size This property returns the number of key-value pairs in the Map
Map.prototype.size
It returns the number of elements in the Map object.
Syntax
1. Map.size
Example
Output
Map Methods
The Map object includes several methods, which are tabulated as follows:
1. Map.prototype.clear() It removes all the keys and values pairs from the M
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.
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
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
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
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
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
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");
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 Properties
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
Output
4
Set { 'Green', 'Red', 'Orange', 'Yellow' }
Set Methods
The set object includes several methods, which are tabulated as follows:
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
Output
7
Set { 'Green', 'Red', 'Orange', 'Yellow', 'Violet', 'Indigo', 'Blue' }
Set.prototype.clear()
It clears all the objects from the sets.
Example
Output
Set.prototype.delete(value)
This method is used to remove the corresponding passed value from the set object.
Example
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
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
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
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
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
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.
1. class Class_name{
2. }
Let us see the illustration for the class expression and class declaration.
1. class Student{
2. constructor(name, age){
3. this.name = name;
4. this.age = age;
5. }
6.
7. }
Example - Class Expression
Syntax
Example
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
Note: Including a constructor definition is mandatory in class because, by default, every class has a
constructor.
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
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
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.
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...
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
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
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:
String Properties
There are some properties of the string that are tabulated as follows:
Syntax
1. string.constructor
Example
Output
Syntax
1. string.length
Example
Output
Syntax
1. object.prototype.name = value;
Example
Output
Daniel Grint
BCA
20
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)
Example
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)
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
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)
Example
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)
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
Output
1. charAt() It provides the char value, which is present at the specified index.
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.
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.
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
Example
Output
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
Output
Hello, World!
Welcome to javaTpoint
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
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.
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:
Output
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
Output
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.
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.
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:
Attributes Description
oncanplaythrough It triggers when media plays till the end without any buffering or stopping.
ondragover It triggers when the element is being dragged over a drop target.
omemptied It triggers when the resource element in media suddenly gets empty.
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.
onloadedmetadata It triggers when the media data and duration of the media element is loaded
onloadstart It triggers when the browser starts the loading of media data.
onmouseover It triggers when you move the mouse pointer over an element.
onmouseout It triggers when the mouse pointer moves out from the element.
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
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
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.
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.
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:
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.
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.
For 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=/ "
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:
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:
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:
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.
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
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.
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/");
Example
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:
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
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
Output
Number.MIN_SAFE_INTEGER
It represents the minimum safe integer in JavaScript (-(253-1)).
Example
Output
Number.MIN_VALUE
It represents the smallest positive numeric value.
Example
Output
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
Number.isNan()
It determines whether the value is Nan or not. It returns true if the value is not a number.
Example
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
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
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
Output
true
false
true
true
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
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
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:
1. Boolean.constructor
Return value
Example
Output
Syntax
1. Boolean.prototype.name = value
Return 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:
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
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.
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
Output
true
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
Example
Output
Welcome back!!
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:
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.
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.
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.
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};
Syntax
App.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:
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.
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:
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.
Syntax
Mobile.js
1. class Nokia{
2. //properties
3. //methods
4. }
5. export default Nokia;
App.js
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
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:
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
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.
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
Example
Output
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
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
Output
.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
Output
.race()
This method is used to return a resolved Promise based on the first referenced Promise that resolves.
Example
Output
Promise 1 is first
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.
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
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.
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.
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.
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.
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
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
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