Es6 Tutorial
Es6 Tutorial
ES6
Audience
This tutorial is designed for the stemplate oftware programmers who have already worked
with JavaScript and wishes to gain in-depth knowledge about the ECMAScript. The tutorial
will give you enough understanding on the functionalities of ECMAScript and also about
ES6, ES7, ES8 and ES9.
Prerequisites
An understanding of JavaScript programming concepts is necessary to gain maximum
knowledge from this tutorial.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com.
i
ES6
Table of Contents
About the Tutorial ....................................................................................................................................i
Audience ..................................................................................................................................................i
Prerequisites ............................................................................................................................................i
JavaScript ................................................................................................................................................1
Brackets ..................................................................................................................................................8
ii
ES6
The const............................................................................................................................................... 20
Assignment Operators........................................................................................................................... 31
The if Statement.................................................................................................................................... 37
iii
ES6
Definite Loop......................................................................................................................................... 45
iv
ES6
How It Works?....................................................................................................................................... 83
v
ES6
MIN_VALUE......................................................................................................................................... 112
Number.isFinite................................................................................................................................... 115
vi
ES6
substr()................................................................................................................................................ 142
vii
ES6
endsWith............................................................................................................................................. 152
viii
ES6
every()................................................................................................................................................. 164
reduce()............................................................................................................................................... 171
ix
ES6
getFullYear()........................................................................................................................................ 190
getMonth().......................................................................................................................................... 192
getTime()............................................................................................................................................. 193
setMinutes()........................................................................................................................................ 201
x
ES6
setUTCFullYear().................................................................................................................................. 204
setUTCMonth().................................................................................................................................... 207
valueof().............................................................................................................................................. 212
xi
ES6
expm1(X)............................................................................................................................................. 220
Abs().................................................................................................................................................... 224
Math.sin(x).......................................................................................................................................... 230
xii
ES6
xiii
ES6
Generator............................................................................................................................................ 260
xiv
ES6
Iterator................................................................................................................................................ 279
set()..................................................................................................................................................... 296
xv
ES6
Number.isFinite................................................................................................................................... 342
xvi
ES6
Math.sign().......................................................................................................................................... 344
Reflect.construct()............................................................................................................................... 357
xvii
ES6
xviii
ES6
xix
1. ES6 − Overview ES6
JavaScript
JavaScript was developed by Brendan Eich, a developer at Netscape Communications
Corporation, in 1995.JavaScript started life with the name Mocha, and was briefly named
LiveScript before being officially renamed to JavaScript. It is a scripting language that is
executed by the browser, i.e. on the client’s end. It is used in conjunction with HTML to
develop responsive webpages.
ECMA Script6’s implementation discussed here covers the following new features:
ECMAScript Versions
There are nine editions of ECMA-262 which are as follows:
1
ES6
ECMAScript Sixth Edition released in 2015, see ES6 chapters for new
6
2015/ES6 features
ECMAScript Eight Edition released in 2017, see ES8 chapters for new
8
2017/ES8 features
2
2. ES6 − Environment ES6
In this chapter, we will discuss the setting up of the environment for ES6.
Text Editor
The text editor helps you to write your source code. Examples of few editors include
Windows Notepad, Notepad++, Emacs, vim or vi etc. Editors used may vary with the
operating systems. The source files are typically named with the extension .js.
Installing Node.js
Node.js is an open source, cross-platform runtime environment for server-side
JavaScript. Node.js is required to run JavaScript without a browser support. It uses Google
V8 JavaScript engine to execute the code. You may download Node.js source code or a
pre-built installer for your platform. Node is available at https://nodejs.org/en/download
Installation on Windows
Download and run the .msi installer for Node.
3
ES6
To verify if the installation was successful, enter the command node –v in the terminal
window.
Installation on Mac OS X
To install node.js on OS X you can download a pre-compiled binary package which makes
a nice and easy installation. Head over to http://nodejs.org/ and click the install button to
download the latest package.
Install the package from the .dmg by following along the install wizard which will install
both node and npm. npm is the Node Package Manager which facilitates installs of
additional packages for Node.js.
4
ES6
Installation on Linux
You need to install a number of dependencies before you can install Node.js and npm.
Ruby and GCC. You’ll need Ruby 1.8.6 or newer and GCC 4.2 or newer.
Homebrew. Homebrew is a package manager originally for the Mac, but it’s been
ported to Linux as Linuxbrew. You can learn more about Homebrew at the
http://brew.shand Linuxbrew at the http://brew.sh/linuxbrew.
Installation on Windows
Download Visual Studio Code for Windows.
5
ES6
Double-click on VSCodeSetup.exe to launch the setup process. This will only take
a minute.
6
ES6
You may directly traverse to the file’s path by a right-click on the file -> open in command
prompt. Similarly, the Reveal in Explorer option shows the file in the File Explorer.
7
ES6
Installation on Mac OS X
Visual Studio Code’s Mac OS X specific installation guide can be found at
https://code.visualstudio.com/Docs/editor/setup
Installation on Linux
Linux specific installation guide for Visual Studio Code can be found at
https://code.visualstudio.com/Docs/editor/setup
Brackets
Brackets is a free open-source editor for web development, created by Adobe Systems. It
is available for Linux, Windows and Mac OS X. Brackets is available at http://brackets.io
8
ES6
You can run DOS prompt/Shell within Brackets itself by adding one more extension
Brackets Shell.
9
ES6
Upon installation, you will find an icon of shell on the right hand side of the editor .
Once you click on the icon, you will see the shell window as shown in the following
screenshot.
10
3. ES6 − Syntax ES6
Syntax defines the set of rules for writing programs. Every language specification defines
its own syntax.
Variables: Represents a named memory block that can store values for the
program.
The following table lists some keywords in JavaScript. Some commonly used keywords are
listed in the following table.
Comments: Used to improve code readability. These are ignored by the JavaScript
engine.
Identifiers: These are the names given to elements in a program like variables,
functions, etc. The rules for identifiers are:
o Identifiers can include both, characters and digits. However, the identifier
cannot begin with a digit.
11
ES6
firstName Var#
first_name first name
num1 first-name
$result 1number
JavaScript is Case-sensitive
JavaScript is case-sensitive. This means that JavaScript differentiates between the
uppercase and the lowercase characters.
Example
console.log("hello world")
console.log("We are learning ES6")
A single line can contain multiple statements. However, these statements must be
separated by a semicolon.
Comments in JavaScript
Comments are a way to improve the readability of a program. Comments can be used to
include additional information about a program like the author of the code, hints about a
function/construct, etc. Comments are ignored by the compiler.
Single-line comments (//): Any text between a // and the end of a line is treated
as a comment.
Multi-line comments (/* */): These comments may span multiple lines.
12
ES6
Example
//this is single line comment
/* This is a
Multi-line comment
*/
Line 2 prints the variable’s value to the prompt. Here, the console refers to the
terminal window. The function log () is used to display the text on the screen.
Step 2: Right-click the Test.js file under the working files option in the project-explorer
window of the Visual Studio Code.
node Test.js
Hello World
13
ES6
Staged Features: These are almost completed features but not considered stable
by the V8 team.
The first category of features is fully supported and turned on by default by node. Staged
features require a runtime - - harmony flag to execute.
A list of component specific CLI flags for Node.js can be found here:
https://nodejs.org/api/cli.html
The code can be transitioned to work in the Strict Mode by including the following:
In the above snippet, the entire code runs as a constrained variant of JavaScript.
JavaScript also allows to restrict, the Strict Mode within a block’s scope as that of a
function. This is illustrated as follows:
v=15
function f1()
{
"use strict";
var v = "Hi! I'm a strict mode script!";
}
In, the above snippet, any code outside the function will run in the non-script mode. All
statements within the function will be executed in the Strict Mode.
14
ES6
Variable Hoisting and Function Hoisting are explained in the subsequent chapters.
15
4. ES6 − Variables ES6
A variable, by definition, is “a named space in the memory” that stores values. In other
words, it acts as a container for values in a program. Variable names are called
identifiers. Following are the naming rules for an identifier:
Identifiers cannot contain spaces and special characters, except the underscore (_)
and the dollar ($) sign.
Type Syntax
A variable must be declared before it is used. ES5 syntax used the var keyword to achieve
the same. The ES5 syntax for declaring a variable is as follows.
Variable initialization refers to the process of storing a value in the variable. A variable
may be initialized either at the time of its declaration or at a later point in time.
The traditional ES5 type syntax for declaring and initializing a variable is as follows:
16
ES6
JavaScriptVariable Scope
The scope of a variable is the region of your program in which it is defined. Traditionally,
JavaScript defines only two scopes-global and local.
Global Scope: A variable with global scope can be accessed from within any part
of the JavaScript code.
Local Scope: A variable with a local scope can be accessed from within a function
where it is declared.
var num=10
function test()
{
var num=100
console.log("value of num in test() "+num)
}
console.log("value of num outside test() "+num)
test()
The variable when referred to within the function displays the value of the locally scoped
variable. However, the variable num when accessed outside the function returns the
globally scoped instance.
17
ES6
"use strict"
function test()
{
var num=100
console.log("value of num in test() "+num)
{
console.log("Inner Block begins")
let num=200
console.log("value of num : "+num)
}
}
test()
The script declares a variable num within the local scope of a function and re-declares it
within a block using the let keyword. The value of the locally scoped variable is printed
when the variable is accessed outside the inner block, while the block scoped variable is
referred to within the inner block.
20
18
ES6
let no =10;
let no =20;
console.log(no);
The above code will throw an error: Identifier 'no' has already been declared. Any variable
declared using the let keyword is assigned the block scope.
<script>
let balance = 5000 // number type
console.log(typeof balance)
</script>
Example
<script>
let count=100
for (let count =1;count<=10;count++){
//inside for loop brackets ,count value starts from 1
console.log("count value inside loop is ",count);
}
//outside for loop brackets ,count value is 100
console.log("count value after loop is",count);
19
ES6
if(count==100){
//inside if brackets ,count value is 50
let count=50;
console.log("count inside if block",count);
}
console.log(count);
</script>
The const
The const declaration creates a read-only reference to a value. It does not mean the
value it holds is immutable, just that the variable identifier cannot be reassigned.
Constants are block-scoped, much like variables defined using the let statement. The value
of a constant cannot change through re-assignment, and it can't be re-declared.
The following rules hold true for a variable declared using the const keyword:
20
ES6
Example
const x=10
x=12 // will result in an error!!
The above code will return an error since constants cannot be reassigned a value.
Constants variable are immutable.
<script>
let income = 100000
const INTEREST_RATE = 0.08
income += 50000 // mutable
console.log("changed income value is ",income)
INTEREST_RATE += 0.01
console.log("changed rate is ",INTEREST_RATE) //Error: not mutable
</script>
<script>
const DEPT_NOS = [10,20,30,50]
DEPT_NOS.push(40)
console.log('dept numbers is ',DEPT_NOS)
21
ES6
console.log('employee ids',EMP_IDS)
//re assigning variable employee ids
EMP_IDS = [2001,2002,2003]
console.log('employee ids after changing',EMP_IDS)
</script>
<script>
// variable company is hoisted to top , var company = undefined
console.log(company); // using variable before declaring
var company = "TutorialsPoint"; // declare and initialized here
console.log(company);
</script>
undefined
TutorialsPoint
22
ES6
<script>
//hoisted to top ; var i = undefined
for (var i=1;i<=5;i++){
console.log(i);
}
console.log("after the loop i value is "+i);
</script>
1
2
3
4
5
after the loop i value is 6
The variable i is declared inside the for loop using the var keyword. The variable i is
accessible outside the loop. However, at times, there might be a need to restrict a
variable's access within a block. We cannot use the var keyword in this scenario. ES6
introduces the let keyword to overcome this limitation.
<script>
var balance = 5000
console.log(typeof balance)
var balance = {message:"hello"}
console.log(typeof balance)
</script>
number
23
ES6
object
24
5. ES6 − Operators ES6
Consider the following expression- 2 + 3. Here in the expression, 2 and 3 are operands
and the symbol + (plus) is the operator. JavaScript supports the following types of
operators:
Arithmetic operators
Logical operators
Relational operators
Bitwise operators
Assignment operators
Ternary/conditional operators
String operators
Type operators
The void operator
Arithmetic Operators
Assume the values in variables a and b are 10 and 5 respectively.
% a % b is 2
25
ES6
Sum: 12
Difference: 8
Product: 20
Quotient : 5
Remainder: 0
Value of num1 after increment: 11
Value of num2 after decrement: 1
26
ES6
Relational Operators
Relational operators test or define the kind of relationship between two entities. Relational
operators return a boolean value, i.e. true/false.
Example
var num1 = 5;
var num2 = 9;
console.log("Value of num1: " + num1);
console.log("Value of num2 :" + num2);
var res = num1 > num2;
console.log("num1 greater than num2: " + res);
res = num1 < num2;
console.log("num1 lesser than num2: " + res);
res = num1 >= num2;
console.log("num1 greater than or equal to num2: " + res);
res = num1 <= num2;
console.log("num1 lesser than or equal to num2: " + res);
res = num1 == num2;
console.log("num1 is equal to num2: " + res);
res = num1 != num2;
console.log("num1 not equal to num2: " + res);
27
ES6
Value of num1: 5
Value of num2 :9
num1 greater than num2: false
num1 lesser than num2: true
num1 greater than or equal to num2: false
num1 lesser than or equal to num2: true
14 num1 is equal to num2: false
16 num1 not equal to num2: true
Logical Operators
Logical operators are used to combine two or more conditions. Logical operators, too,
return a Boolean value. Assume the value of variable A is 10 and B is 20.
Example
var avg = 20;
var percentage = 90;
console.log("Value of avg: " + avg + " ,value of percentage: " + percentage);
var res = ((avg > 50) && (percentage > 80));
console.log("(avg>50)&&(percentage>80): ", res);
var res = ((avg > 50) || (percentage > 80));
console.log("(avg>50)||(percentage>80): ", res);
var res = !((avg > 50) && (percentage > 80));
console.log("!((avg>50)&&(percentage>80)): ", res);
28
ES6
Short-circuit Operators
The && and || operators are used to combine expressions.
The && operator returns true only when both the conditions return true. Let us consider
an expression:
var a=10
var result=( a<10 && a>5)
In the above example, a<10 and a>5 are two expressions combined by an && operator.
Here, the first expression returns false. However, the && operator requires both the
expressions to return true. So, the operator skips the second expression.
The || operator returns true, if one of the expressions return true. For example:
var a=10
var result=( a>5 || a<10)
In the above snippet, two expressions a>5 and a<10 are combined by a || operator. Here,
the first expression returns true. Since, the first expression returns true, the || operator
skips the subsequent expression and returns true.
Due to this behavior of the && and || operator, they are called as short-circuit operators.
Bitwise Operators
JavaScript supports the following bitwise operators. The following table summarizes
JavaScript's bitwise operators.
Bitwise OR a|b Returns a one in each bit position for which the
corresponding bits of either or both operands are ones
Returns a one in each bit position for which the
Bitwise XOR a^b corresponding bits of either but not both operands are
ones
29
ES6
Sign-
Shifts a in binary representation b (< 32) bits to the
propagating a >> b
right, discarding bits shifted off
right shift
Example
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var result;
result = (a & b);
console.log("(a & b) => ", result);
result = (a | b);
console.log("(a | b) => ", result);
result = (a ^ b);
console.log("(a ^ b) => ", result);
result = (~b);
console.log("(~b) => ", result);
result = (a << b);
console.log("(a << b) => ", result);
result = (a >> b);
console.log("(a >> b) => ", result);
Output
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
30
ES6
Assignment Operators
The following table summarizes Assignment operators.
= (Simple Assignment)
1 Assigns values from the right side operand to the left side operand
It adds the right operand to the left operand and assigns the result to the left
2
operand.
Example: C += A is equivalent to C = C + A
It subtracts the right operand from the left operand and assigns the result to
3
the left operand.
Example: C -= A is equivalent to C = C - A
It multiplies the right operand with the left operand and assigns the result to
4
the left operand.
Example: C *= A is equivalent to C = C * A
Note: The same logic applies to Bitwise operators, so they will become <<=, >>=, >>=,
&=, |= and ^=
Example
var a = 12;
var b = 10;
a = b;
31
ES6
a=b: 10
a+=b: 20
a-=b: 10
a*=b: 100
a/=b: 10
a%=b: 0
Miscellaneous Operators
Following are some of the miscellaneous operators.
var x=4
var y=-x;
console.log("value of x: ",x); //outputs 4
console.log("value of y: ",y); //outputs -4
value of x: 4
value of y: -4
32
ES6
var msg="hello"+"world"
console.log(msg)
helloworld
The concatenation operation doesn’t add a space between the strings. Multiple strings can
be concatenated in a single statement.
Where,
Example
var num=-2
var result= num > 0 ?"positive":"non-positive"
console.log(result)
Line 2 checks whether the value in the variable num is greater than zero. If num is set to
a value greater than zero, it returns the string “positive” else a “non-positive” string is
returned.
non-positive
typeof operator
It is a unary operator. This operator returns the data type of the operand. The following
table lists the data types and the values returned by the typeof operator in JavaScript.
33
ES6
Number "number"
String "string"
Boolean "boolean"
Object "object"
var num=12
console.log(typeof num); //output: number
number
Spread Operator
ES6 provides a new operator called the spread operator. The spread operator is
represented by three dots “...” . The spread operator converts an array into individual
array elements.
<script>
function addThreeNumbers(a,b,c){
return a+b+c;
}
sum is : 60
34
ES6
sum is 6
Example
<script>
</script>
<script>
//copy object
let student1 ={firstName:'Mohtashim',company:'TutorialsPoint'}
let student2 ={...student1}
console.log(student2)
//concatenate objects
35
ES6
36
6. ES6 − Decision Making ES6
Statement Description
An ‘if’ statement consists of a Boolean expression
if statement
followed by one or more statements
An ‘if’ statement can be followed by an optional ‘else’
if...else statement statement, which executes when the Boolean
expression is false
The else.. if ladder / You can use one ‘if’ or ‘else if’ statement inside
nested if statements another ‘if’ or ‘else if’ statement(s)
A ‘switch’ statement allows a variable to be tested for
switch statement
equality against a list of values
The if Statement
The ‘if…else’ construct evaluates a condition before a block of code is executed.
37
ES6
if(boolean_expression)
{
// statement(s) will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true, then the block of code inside the if statement
will be executed. If the Boolean expression evaluates to false, then the first set of code
after the end of the if statement (after the closing curly brace) will be executed.
Flowchart
Example
var num=5
if (num>0)
{
console.log("number is positive")
}
number is positive
38
ES6
The above example will print “number is positive” as the condition specified by the if block
is true.
if(boolean_expression)
{
// statement(s) will execute if the Boolean expression is true
}
else
{
// statement(s) will execute if the Boolean expression is false
}
Flowchart
The if block guards the conditional expression. The block associated with the if statement
is executed if the Boolean expression evaluates to true. The if block may be followed by
an optional else statement. The instruction block associated with the else block is executed
if the expression evaluates to false.
39
ES6
The above example prints whether the value in a variable is even or odd. The if block
checks the divisibility of the value by 2 to determine the same.
Even
if (boolean_expression1)
{
//statements if the expression1 evaluates to true
}
else if (boolean_expression2)
{
//statements if the expression2 evaluates to true
}
else
{
//statements if both expression1 and expression2 result to false
}
When using if…else statements, there are a few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
40
ES6
2 is positive
switch(variable_expression)
{
case constant_expr1:
{
//statements;
break;
}
case constant_expr2:
{
//statements;
41
ES6
break;
}
default:
{
//statements;
break;
}
}
The value of the variable_expression is tested against all cases in the switch. If the
variable matches one of the cases, the corresponding code block is executed. If no case
expression matches the value of the variable_expression, the code within the default block
is associated.
The data type of the variable_expression and the constant expression must match.
Unless you put a break after each block of code, the execution flows into the next
block.
Flowchart
42
ES6
Example: switch…case
var grade="A";
switch(grade)
{
case "A":
{
console.log("Excellent");
break;
}
case "B":
{
console.log("Good");
break;
}
43
ES6
case "C":
{
console.log("Fair");
break;
}
case "D":
{
console.log("Poor");
break;
}
default:
{
console.log("Invalid choice");
break;
}
}
Excellent
The example verifies the value of the variable grade against the set of constants (A, B, C,
D, and E) and executes the corresponding blocks. If the value in the variable doesn’t match
any of the constants mentioned above, the default block will be executed.
44
7. ES6 − Loops ES6
At times, certain instructions require repeated execution. Loops are an ideal way to do the
same. A loop represents a set of instructions that must be repeated. In a loop’s context,
a repetition is termed as an iteration.
Definite Loop
A loop whose number of iterations are definite/fixed is termed as a definite loop. The ‘for
loop’ is an implementation of a definite loop.
var num=5
var factorial=1;
for( let i = num ; i >= 1; i-- )
{
factorial *= i ;
}
console.log(factorial);
45
ES6
The for loop has three parts: the initializer (i=num), the condition ( i>=1) and the final
expression (i--).
The program calculates the factorial of the number 5 and displays the same. The for loop
generates the sequence of numbers from 5 to 1, calculating the product of the numbers
in every iteration.
Multiple assignments and final expressions can be combined in a for loop, by using the
comma operator (,). For example, the following for loop prints the first eight Fibonacci
numbers:
Example
"use strict"
for(let temp, i=0, j=1; j<30; temp = i, i = j, j = i + temp)
console.log(j);
1
1
2
3
5
8
13
21
In each iteration, one property from the object is assigned to the variable name and this
loop continues till all the properties of the object are exhausted.
46
ES6
Example
var obj = {a:1, b:2, c:3};
The above example illustrates iterating an object using the for... in loop. The following
output is displayed on successful execution of the code.
1
2
3
Example
for (let val of[12 , 13 , 123]){
console.log(val)
}
12
13
123
47
ES6
Indefinite Loop
An indefinite loop is used when the number of iterations in a loop is indeterminate or
unknown.
while loop
do…while loop
Flow chart
while (expression)
{
Statement(s) to be executed if expression is true
}
48
ES6
Example
var num=5;
var factorial=1;
while(num >=1)
{
factorial=factorial * num;
num--;
}
console.log("The factorial is "+factorial);
The above code uses a while loop to calculate the factorial of the value in the variable
num.
Flowchart
49
ES6
do{
Statement(s) to be executed;
} while (expression);
Note: Don’t miss the semicolon used at the end of the do...while loop.
Example
var n=10;
do
{
console.log(n);
n--;
} while(n>=0);
10
9
8
7
6
5
4
3
2
1
0
var n=10;
do
{
console.log(n);
n--;
50
ES6
}
while(n>=0);
while loop:
var n=10;
while(n>=0)
{
console.log(n);
n--;
}
In the above example, the while loop is entered only if the expression passed to while
evaluates to true. In this example, the value of n is not greater than zero, hence the
expression returns false and the loop is skipped.
On the other hand, the do…while loop executes the statement once. This is because the
initial iteration does not consider the boolean expression. However, for the subsequent
iteration, the while checks the condition and takes the control out of the loop.
Example
var i=1
while(i<=10)
{
if (i % 5 == 0)
{
console.log("The first multiple of 5 between 1 and 10 is : "+i)
break //exit the loop if the first multiple is found
}
i++
}
The above code prints the first multiple of 5 for the range of numbers within 1 to 10.
51
ES6
If a number is found to be divisible by 5, the if construct forces the control to exit the loop
using the break statement. The following output is displayed on successful execution of
the above code.
var num=0
var count=0;
for(num=0;num<=20;num++)
{
if (num % 2==0)
{
continue
}
count++
}
console.log(" The count of odd values between 0 and 20 is: "+count)
The above example displays the number of even values between 0 and 20. The loop exits
the current iteration if the number is even. This is achieved using the continue statement.
Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label
name. Also, there should not be any other statement in between a label name and an
associated loop.
52
ES6
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 2
Outerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 4
53
ES6
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
54
8. ES6 − Functions ES6
Functions are the building blocks of readable, maintainable, and reusable code. Functions
are defined using the function keyword. Following is the syntax for defining a standard
function.
function function_name()
{
// function body
}
To force execution of the function, it must be called. This is called as function invocation.
Following is the syntax to invoke a function.
function_name()
The example defines a function test(). A pair of delimiters ( { } ) define the function body.
It is also called as the function scope. A function must be invoked to force its execution.
function called
Classification of Functions
Functions may be classified as Returning and Parameterized functions.
Returning functions
Functions may also return the value along with control, back to the caller. Such functions
are called as returning functions.
function function_name()
{
//statements
return value;
}
A function can return at the most one value. In other words, there can be only one
return statement per function.
function retStr()
{
return "hello world!!!"
}
var val=retStr()
console.log(val)
The above Example defines a function that returns the string “hello world!!!” to the caller.
The following output is displayed on successful execution of the above code.
hello world!!!
Parameterized functions
Parameters are a mechanism to pass values to functions. Parameters form a part of the
function’s signature. The parameter values are passed to the function during its invocation.
Unless explicitly specified, the number of values passed to a function must match the
number of parameters defined.
56
ES6
function add(a, b = 1) {
return a+b;
}
console.log(add(4))
The above function, sets the value of b to 1 by default. The function will always consider
the parameter b to bear the value 1 unless a value has been explicitly passed. The
following output is displayed on successful execution of the above code.
The parameter’s default value will be overwritten if the function passes a value explicitly.
function add(a, b = 1) {
return a+b;
}
console.log(add(4,2))
The above code sets the value of the parameter b explicitly to 2, thereby overwriting its
default value. The following output is displayed on successful execution of the above code.
57
ES6
Example 1
The following example shows a function which takes two parameters and returns their
sum. The second parameter has a default value of 10. This means, if no value is passed
to the second parameter, its value will be 10.
<script>
function addTwoNumbers(first,second=10){
console.log('first parameter is :',first)
console.log('second parameter is :',second)
return first+second;
}
first parameter is : 20
second parameter is : 10
case 1 sum: 30
first parameter is : 2
second parameter is : 3
case 2 sum: 5
first parameter is : undefined
second parameter is : 10
case 3 sum: NaN
first parameter is : 1
second parameter is : null
case 4 sum 1
first parameter is : 3
second parameter is : 10
case 5 sum 13
58
ES6
Example 2
<script>
let DEFAULT_VAL = 30
function addTwoNumbers(first,second=DEFAULT_VAL){
console.log('first parameter is :',first)
console.log('second parameter is :',second)
return first+second;
}
console.log("case 1 sum",addTwoNumbers(1))
console.log("case 2 sum",addTwoNumbers(3,undefined))
</script>
first parameter is : 1
second parameter is : 30
case 1 sum 31
first parameter is : 3
second parameter is : 30
case 2 sum 33
59
ES6
Rest Parameters
Rest parameters are similar to variable arguments in Java. Rest parameters doesn’t
restrict the number of values that you can pass to a function. However, the values passed
must all be of the same type. In other words, rest parameters act as placeholders for
multiple arguments of the same type.
To declare a rest parameter, the parameter name is prefixed with three periods, known
as the spread operator. The following example illustrates the same.
function fun1(...params) {
console.log(params.length);
}
fun1();
fun1(5);
fun1(5, 6, 7);
0
1
3
Anonymous Function
Functions that are not bound to an identifier (function name) are called as anonymous
functions. These functions are dynamically declared at runtime. Anonymous functions can
accept inputs and return outputs, just as standard functions do. An anonymous function
is usually not accessible after its initial creation.
60
ES6
hello
Following is the syntax to create a function using Function() constructor along with the
new operator.
The Function() constructor expects any number of string arguments. The last argument is
the body of the function – it can contain arbitrary JavaScript statements, separated from
each other by semicolons.
The Function() constructor is not passed any argument that specifies a name for the
function it creates.
61
ES6
result = func(10,20);
console.log("The product : "+result)
}
product()
In the above example, the Function() constructor is used to define an anonymous function.
The function accepts two parameters and returns their product.
Example: Recursion
function factorial(num)
{
if(num<=0)
{
return 1;
}
else
{
return (num * factorial(num-1) )
}
}
console.log(factorial(6))
In the above example the function calls itself. The following output is displayed on
successful execution of the above code.
720
62
ES6
The function calls itself using a pair of parentheses (). The following output is displayed
on successful execution of the above code.
Hello World
Lambda Functions
Lambda refers to anonymous functions in programming. Lambda functions are a concise
mechanism to represent anonymous functions. These functions are also called as Arrow
functions.
The fat arrow notation/lambda notation (=>): It is also called as the goes to
operator.
Tip: By convention, the use of a single letter parameter is encouraged for a compact and
precise function declaration.
Lambda Expression
It is an anonymous function expression that points to a single line of code. Following is
the syntax for the same.
The Example declares a lambda expression function. The function returns the sum of 10
and the argument passed.
20
63
ES6
Lambda Statement
It is an anonymous function declaration that points to a block of code. This syntax is used
when the function body spans multiple lines. Following is the syntax of the same.
The function’s reference is returned and stored in the variable msg. The following output
is displayed on successful execution of the above code.
function invoked
Syntactic Variations
Optional parentheses for a single parameter
var msg=x=>
{
console.log(x)
}
msg(10)
64
ES6
The fundamental difference between the two is that, function declarations are parsed
before their execution. On the other hand, function expressions are parsed only when the
script engine encounters it during an execution.
When the JavaScript parser sees a function in the main code flow, it assumes function
declaration. When a function comes as a part of a statement, it is a function expression.
Function Hoisting
Like variables, functions can also be hoisted. Unlike variables, function declarations when
hoisted, hoists the function definition rather than just hoisting the function’s name.
hoist_function();
function hoist_function() {
console.log("foo");
}
foo
However, function expressions cannot be hoisted. The following code snippet illustrates
the same.
Example 1: IIFE
var main = function()
{
var loop =function()
65
ES6
{
for(var x=0;x<5;x++)
{
console.log(x);
}
}();
console.log("x can not be accessed outside the block scope x value
is :"+x);
}
main();
Example 2:IIFE
var main = function()
{
(function()
{
for(var x=0;x<5;x++)
{
console.log(x);
}
})();
console.log("x can not be accessed outside the block scope x value is :"+x);
}
main();
0
1
2
3
4
5
Uncaught ReferenceError: x is not defined
66
ES6
Generator Functions
When a normal function is invoked, the control rests with the function called until it
returns. With generators in ES6, the caller function can now control the execution of a
called function. A generator is like a regular function except that:
The function can yield control back to the caller at any point.
When you call a generator, it doesn’t run right away. Instead, you get back an
iterator. The function runs as you call the iterator’s next method.
Generators are denoted by suffixing the function keyword with an asterisk; otherwise,
their syntax is identical to regular functions.
"use strict"
function* rainbow() { // the asterisk marks this as a generator
yield 'red';
yield 'orange';
yield 'yellow';
yield 'green';
yield 'blue';
yield 'indigo';
yield 'violet';
}
for(let color of rainbow()) {
console.log(color);
}
Generators enable two-way communication between the caller and the called function.
This is accomplished by using the yield keyword.
function* ask() {
const name = yield "What is your name?";
const sport = yield "What is your favorite sport?";
return `${name}'s favorite sport is ${sport}`;
}
const it = ask();
console.log(it.next());
console.log(it.next('Ethan'));
67
ES6
console.log(it.next('Cricket'));
The it.next() yields “What is your name”. The generator is paused. This is done by
the yield keyword.
The call it.next(“Ethan”) assigns the value Ethan to the variable name and yields
“What is your favorite sport?” Again the generator is paused.
The call it.next(“Cricket”) assigns the value Cricket to the variable sport and
executes the subsequent return statement.
Arrow Functions
Arrow functions which are introduced in ES helps in writing the functions in JavaScript in
a concise manner. Let us now learn about the same in detail.
<script>
setTimeout(function(){
console.log('Learning at TutorialsPoint is fun!!')
},1000)
</script>
68
ES6
Tip: By convention, the use of a single letter parameter is encouraged for a compact and
precise arrow function declaration.
Syntax
//Arrow function that points to a single line of code
()=>some_expression
OR
OR
(param1,param2)=>{//some statement}
69
ES6
<script>
console.log(isEven(10))
</script>
30
true
70
ES6
<script>
const names = ['TutorialsPoint','Mohtashim','Bhargavi','Raja']
names.map((element,index)=>{
console.log('inside arrow function')
console.log('index is '+index+' element value is :'+element)
})
</script>
71
ES6
<script>
setTimeout(()=>{
console.log('Learning at TutorialsPoint is fun!!')
},1000)
</script>
<script>
//constructor function
function Student(rollno,firstName,lastName) {
this.rollno = rollno;
this.firstName = firstName;
this.lastName = lastName;
this.fullNameUsingAnonymous = function(){
setTimeout(function(){
this.fullNameUsingArrow = function(){
setTimeout(()=>{
72
ES6
}
const s1 = new Student(101,'Mohammad','Mohtashim')
s1.fullNameUsingAnonymous();
s1.fullNameUsingArrow();
</script>
When an anonymous function is used with setTimeout(), the function gets invoked after
2000 milliseconds. A new instance of “this” is created and it shadows the instance of the
Student function. So, the value of this.firstName and this.lastName will
be undefined. The function doesn't use the lexical scope or the context of current
execution. This problem can be solved by using an arrow function.
undefined undefined
Mohammad Mohtashim
73
9. ES6 − Events ES6
JavaScript is meant to add interactivity to your pages. JavaScript does this using a
mechanism using events. Events are a part of the Document Object Model (DOM) Level
3 and every HTML element contains a set of events that can trigger JavaScript Code.
Event Handlers
On the occurrence of an event, the application executes a set of related tasks. The block
of code that achieves this purpose is called the eventhandler. Every HTML element has
a set of events associated with it. We can define how the events will be processed in
JavaScript by using event handlers.
Example
<html>
<head>
<script type="text/javascript">
function sayHello() {
document.write ("Hello World")
}
</script>
</head>
<body>
<p> Click the following button and see result</p>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
onsubmitEvent Type
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
The following example shows how to use onsubmit. Here we are calling a validate()
function before submitting a form data to the webserver. If validate() function returns
true, the form will be submitted, otherwise it will not submit the data.
Example
<html>
<head>
<script type="text/javascript">
function validation() {
all validation goes here
.........
return either true or false
}
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
75
ES6
Example
<html>
<head>
<script type="text/javascript">
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
Onabort script
76
ES6
77
ES6
79
ES6
80
ES6
81
ES6
82
10. ES6 − Cookies ES6
Web Browsers and Servers use HTTP protocol to communicate. HTTP is stateless protocol,
i.e., it doesn’t maintain the client’s data across multiple requests made by the client. This
complete request-response cycle between the client and the server is defined as a
session. Cookies are the default mechanism used by browsers to store data pertaining to
a user’s session.
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The browser
may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard
drive. Now, when the visitor arrives at another page on your site, the browser sends the
same cookie to the server for retrieval. Once retrieved, your server knows/remembers
what was stored earlier.
Expires: The date the cookie will expire. If this is blank, the cookie will expire
when the visitor quits the browser.
Path: The path to the directory or web page that sets the cookie. This may be
blank, if you want to retrieve the cookie from any directory or page.
Secure: If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value: Cookies are set and retrieved in the form of key-value pairs.
Cookies were originally designed for CGI programming. The data contained in a cookie is
automatically transmitted between the web browser and the web server, so CGI scripts on
the server can read and write cookie values that are stored on the client side.
JavaScript can also manipulate cookies using the cookie property of the Document object.
JavaScript can read, create, modify, and delete the cookies that apply to the current web
page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie
object, which looks like this.
document.cookie = "key1=value1;key2=value2;expires=date";
83
ES6
Here, the ‘expires’ attribute is optional. If you provide this attribute with a valid date or
time, then the cookie will expire on the given date or time and thereafter, the cookies'
value will not be accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For this reason,
you may want to use the JavaScript escape() function to encode the value before storing
it in the cookie. If you do this, you will also have to use the corresponding unescape()
function when you read the cookie value.
Example
<html>
<head>
<script type="text/javascript">
function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert ("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>
84
ES6
Now your machine has a cookie called name. You can set multiple cookies using multiple
key=value pairs separated by comma.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the
document.cookie object is the cookie. So you can use this string whenever you want to
access the cookie. The document.cookie string will keep a list of name=value pairs
separated by semicolons, where the name is the name of a cookie and the value is its
string value.
You can use strings' split() function to break a string into key and values as shown in the
following example.
Example
<html>
<head>
<script type="text/javascript">
function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
}
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
85
ES6
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Note: Here, length is a method of Array class which returns the length of an array.
There may be some other cookies already set on your machine. The above code will display
all the cookies set on your machine.
Example
<html>
<head>
<script type="text/javascript">
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
86
ES6
Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie
return nothing. To do this, you just need to set the expiry date to a time in the past. The
following example illustrates how to delete a cookie by setting its expiry date to one month
behind the current date.
Example
<html>
<head>
<script type="text/javascript">
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
87
ES6
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
88
11. ES6 − Page Redirect ES6
Redirect is a way to send both users and search engines to a different URL from the one
they originally requested. Page redirection is a way to automatically redirect a web page
to another web page. The redirected page is often on the same website, or it can be on a
different website or a web server.
Example
<!DOCTYPE html>
<html>
<head>
<script>
function newLocation() {
window.location="http://www.xyz.com";
}
</script>
</head>
<body>
<input type="button" value="Go to new location" onclick="newLocation()">
</body>
</html>
location.replace()
The other most frequently used method is the replace() method of window.location
object, it will replace the current document with a new one. In replace() method, you can
pass a new URL to replace() method and it will perform an HTTP redirect.
89
ES6
window.location.replace("http://www.abc.com");
location.assign()
The location.assign() method loads a new document in the browser window.
window.location.assign("http://www.abc.org");
location.reload()
The location.reload() method reloads the current document in the browser window.
window.location.reload("http://www.yahoo.com");
window.navigate()
The window.navigate() method is similar to assigning a new value to the
window.location.href property. Because it is only available in MS Internet Explorer, so you
should avoid using this in cross-browser development.
window.navigate("http://www.abc.com");
90
12. ES6 − Dialog Boxes ES6
JavaScript supports three important types of dialog boxes. These dialog boxes can be used
to raise and alert, or to get confirmation on any input or to have a kind of input from the
users. Here we will discuss each dialog box one by one.
Nonetheless, an alert box can still be used for friendlier messages. Alert box provides only
one button "OK" to select and proceed.
Example
<html>
<head>
<script type="text/javascript">
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>
91
ES6
If the user clicks on the OK button, the window method confirm() will return true. If the
user clicks on the Cancel button, then confirm() returns false. You can use a confirmation
dialog box as follows.
Example
<html>
<head>
<script type="text/javascript">
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}
else{
Document.write ("User does not want to continue!");
return false;
}
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
92
ES6
This dialog box is displayed using a method called prompt() which takes two parameters:
(i) a label which you want to display in the text box and (ii) a default string to display in
the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the
window method prompt() will return the entered value from the text box. If the user clicks
the Cancel button, the window method prompt() returns null.
Example
<html>
<head>
<script type="text/javascript">
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
93
ES6
94
13. ES6 − void Keyword ES6
void is an important keyword in JavaScript which can be used as a unary operator that
appears before its single operand, which may be of any type. This operator specifies an
expression to be evaluated without returning a value. The operator evaluates a given
expression and then returns undefined.
void expression
hello world
95
ES6
</a>
Save the above file as an HTML document and open it in the browser. The first hyperlink,
when clicked evaluates the javascript :alert(“hello”) and is passed to the void() operator.
However, since the void operator returns undefined, no result is displayed on the page.
On the other hand, the second hyperlink when clicked displays an alert dialog.
96
14. ES6 − Page Printing ES6
Many times you would like to place a button on your webpage to print the content of that
web page via an actual printer. JavaScript helps you implement this functionality using the
print function of the window object.
The JavaScript print function window.print() prints the current webpage when executed.
You can call this function directly using the onclick event as shown in the following
example.
Example
<html>
<body>
<form>
<input type="button" value="Print" onclick="window.print()"/>
</form>
</body>
</html>
97
15. ES6 − Objects ES6
JavaScript supports extending data types. JavaScript objects are a great way to define
custom data types.
An object is an instance which contains a set of key value pairs. Unlike primitive data
types, objects can represent multiple or complex values and can change over their life
time. The values can be scalar values or functions or even array of other objects.
Object Initializers
Like the primitive types, objects have a literal syntax: curly braces ({and}). Following is
the syntax for defining an object.
The contents of an object are called properties (or members), and properties consist of
a name (or key) and value. Property names must be strings or symbols, and values can
be any type (including other objects).
Like all JavaScript variables, both the object name (which could be a normal variable) and
the property name are case sensitive. You access the properties of an object with a simple
dot-notation.
objectName.propertyName
98
ES6
console.log(person.lastname)
console.log(person.func())
The above Example, defines an object person. The object has three properties. The third
property refers to a function.
Tom
Hanks
Hello!!
In ES6, assigning a property value that matches a property name, you can omit the
property value.
Example
var foo = 'bar'
var baz = { foo }
console.log(baz.foo)
The above code snippet defines an object baz. The object has a property foo. The property
value is omitted here as ES6 implicitly assigns the value of the variable foo to the object’s
key foo.
bar
With this shorthand syntax, the JS engine looks in the containing scope for a variable with
the same name. If it is found, that variable’s value is assigned to the property. If it is not
found, a Reference Error is thrown.
99
ES6
Object_name.property_key
OR
Object_name["property_key"]
Example
var myCar = new Object();
myCar.make = "Ford"; //define an object
myCar.model = "Mustang";
myCar.year = 1987;
Ford
Mustang
1987
Example
var myCar = new Object();
myCar.make = "Ford";
console.log(myCar["model"])
undefined
100
ES6
Note: An object property name can be any valid JavaScript string, or anything that can
be converted to a string, including the empty string. However, any property name that is
not a valid JavaScript identifier (for example, a property name that has a space or a
hyphen, or that starts with a number) can only be accessed using the square bracket
notation.
Properties can also be accessed by using a string value that is stored in a variable. In other
words, the object’s property key can be a dynamic value. For example: a variable. The
said concept is illustrated in the following example.
Example
var myCar= new Object()
var propertyName = "make";
myCar[propertyName] = "Ford";
console.log(myCar.make)
Ford
Constructor Function
An object can be created using the following two steps:
function function_name()
{
this.property_name=value
}
The ‘this’ keyword refers to the current object in use and defines the object’s property.
Object_name.property_name
The new keyword invokes the function constructor and initializes the function’s property
keys.
101
ES6
Ford
F123
A new property can always be added to a previously defined object. For example, consider
the following code snippet:
function Car()
{
this.make="Ford"
}
var obj=new Car()
obj.model="F123"
console.log(obj.make)
console.log(obj.model)
Ford
F123
102
ES6
Example
var roles = {
type: "Admin", // Default value of properties
displayType : function() { // Method which will display type of role
console.log(this.type);
}
}
The above example defines an object -roles and sets the default values for the properties.
Two new instances are created that override the default properties value for the object.
Admin
Guest
Object.assign(target, ...sources)
103
ES6
Tom
E1001
{ a: 10, b: 20, c: 30 }
{ a: 10, b: 20, c: 30 }
Note: Unlike copying objects, when objects are merged, the larger object doesn’t maintain
a new copy of the properties. Rather it holds the reference to the properties contained in
the original objects. The following example explains this concept.
var o1 = { a: 10 };
var obj = Object.assign(o1);
obj.a++
console.log("Value of 'a' in the Merged object after increment ")
console.log(obj.a);
console.log("value of 'a' in the Original Object after increment ")
console.log(o1.a);
104
ES6
Deleting Properties
You can remove a property by using the delete operator. The following code shows how
to remove a property.
Example
// Creates a new object, myobj, with two properties, a and b.
var myobj = new Object;
myobj.a = 5;
myobj.b = 12;
// Removes the ‘a’ property
delete myobj.a;
console.log ("a" in myobj) // yields "false"
false
The code snippet deletes the property from the object. The example prints false as the in
operator doesn’t find the property in the object.
Comparing Objects
In JavaScript, objects are a reference type. Two distinct objects are never equal, even if
they have the same properties. This is because, they point to a completely different
memory address. Only those objects that share a common reference yields true on
comparison.
105
ES6
In the above example, val1 and val2 are two distinct objects that refer to two different
memory addresses. Hence on comparison for equality, the operator will return false.
In the above example, the contents in val1 are assigned to val2, i.e. the reference of the
properties in val1 are shared with val2. Since, the objects now share the reference to the
property, the equality operator will return true for two distinct objects that refer to two
different memory addresses. Hence on comparison for equality, the operator will return
false.
Object De-structuring
The term destructuring refers to breaking up the structure of an entity. The destructuring
assignment syntax in JavaScript makes it possible to extract data from arrays or objects
into distinct variables. The same is illustrated in the following example.
Example 1
When destructuring an object the variable names and the object property names must
match.
<script>
let student = {
rollno:20,
name:'Prijin',
cgpa:7.2
}
console.log(name)
console.log(cgpa)
106
ES6
let {name:student_name,cgpa:student_cgpa}=student
console.log(student_cgpa)
console.log("student_name",student_name)
</script>
Prijin
7.2
7.2
student_name Prijin
Example 2
If the variable and assignment are in two different steps, then the destructuring object
syntax will be surrounded by () as shown in the example ({rollno} = student):
<script>
let student = {
rollno:20,
name:'Prijin',
cgpa:7.2
}
({rollno} = student)
console.log(rollno)
107
ES6
20
1001
2000
0.1
Example 3
The below example shows destructuring using the rest operator and how to destruct
nested objects.
<script>
// rest operator with object destructuring
let customers= {
c1:101,
c2:102,
c3:103
}
//nested objects
let emp = {
id:101,
address:{
city:'Mumbai',
pin:1234
}
}
108
ES6
</script>
101
{c2: 102, c3: 103}
{city: "Mumbai", pin: 1234}
Mumbai
109
16. ES6 − Number ES6
The Number object represents numerical date, either integers or floating-point numbers.
In general, you do not need to worry about Number objects because the browser
automatically converts number literals to instances of the number class.
In the place of number, if you provide any non-number argument, then the argument
cannot be converted into a number, it returns NaN (Not-a-Number).
Number Properties
Property Description
110
ES6
EPSILON
This property represents the smallest interval between two representable numbers.
Example
var interval=Number.EPSILON
console.log(interval)
Output
2.220446049250313e-16
MAX_SAFE_INTEGER
This property represents the maximum safe integer in JavaScript i.e. (2^ 53 - 1)
Example
var interval=Number.MAX_SAFE_INTEGER
console.log(interval)
Output
9007199254740991
MAX_VALUE
The Number.MAX_VALUE property belongs to the static Number object. It represents
constants for the largest possible positive numbers that JavaScript can work with.
Syntax
var val = Number.MAX_VALUE;
Example
var val = Number.MAX_VALUE;
console.log("Value of Number.MAX_VALUE : " + val );
Output
Value of Number.MAX_VALUE : 1.7976931348623157e+308
111
ES6
MIN_SAFE_INTEGER
The Number.MIN_SAFE_INTEGER constant represents the minimum safe integer in
JavaScript (-(2^ 53 - 1)). The MIN_SAFE_INTEGER constant has a value of -
9007199254740991.
Syntax
var val = Number.MIN_SAFE_INTEGER;
Example
var val = Number.MIN_SAFE_INTEGER;
console.log("Value of Number. MIN_SAFE_INTEGER: " + val );
Output
Value of Number. MIN_SAFE_INTEGER: -9007199254740991
MIN_VALUE
The Number.MIN_VALUE property belongs to the static Number object. It represents
constants for the smallest possible positive numbers that JavaScript can work with.
Syntax
var val = Number.MIN_VALUE;
Example
var val = Number.MAX_VALUE;
console.log("Value of Number.MIN_VALUE : " + val );
Output
Value of Number.MIN_VALUE : 1.7976931348623157e+308
112
ES6
Nan
Unquoted literal constant NaN is a special value representing Not-a-Number. Since NaN
always compares unequal to any number, including NaN, it is usually used to indicate an
error condition for a function that should return a valid number.
Syntax
var val = Number.NaN;
Example
var dayOfMonth = 50;
if (dayOfMonth < 1 || dayOfMonth > 31)
{
dayOfMonth = Number.NaN
console.log("Day of Month must be between 1 and 31.")
}
else
{
console.log("day of month "+dayOfMonth)
}
NEGATIVE_INFINITY
This is a special numeric value representing a value less than Number.MIN_VALUE. This
value is represented as "-Infinity". It resembles an infinity in its mathematical behavior.
For example, anything multiplied by NEGATIVE_INFINITY is NEGATIVE_INFINITY, and
anything divided by NEGATIVE_INFINITY is zero. Because NEGATIVE_INFINITY is a
constant, it is a read-only property of Number.
Syntax
var val = Number.NEGATIVE_INFINITY;
Example
var val = Number.NEGATIVE_INFINITY;
console.log("Value of Number.NEGATIVE_INFINITY : " + val );
113
ES6
Output
Value of Number.NEGATIVE_INFINITY: -Infinity
POSITIVE_INFINITY
This is a special numeric value representing any value greater than Number.MAX_VALUE.
This value is represented as "Infinity". It resembles an infinity in its mathematical
behavior. For example, anything multiplied by POSITIVE_INFINITY is POSITIVE_INFINITY,
and anything divided by POSITIVE_INFINITY is zero. As POSITIVE_INFINITY is a constant,
it is a read-only property of Number.
Syntax
var val = Number.POSITIVE_INFINITY;
Example
var val = Number.POSITIVE_INFINITY;
console.log("Value of Number.POSITIVE_INFINITY : " + val );
Output:
Value of Number.POSITIVE_INFINITY : Infinity
Number Methods
Method Description
114
ES6
Number.isNaN()
The Number.isNaN() method determines whether the passed value is NaN.
Syntax
var res=Number.isNaN(value);
Parameter Details
Value to determine if it is a NaN
Return Value
Returns a Boolean value true if the value is a not a number.
Example
var res=Number.isNaN(10);
console.log(res);
Number.isFinite
The Number.isFinite() method determines whether the passed value is a finite number.
Syntax
var res=Number.isFinite(value);
Parameter Details
Value to be tested for finiteness.
Return Value
Returns a Boolean value, true or false.
Example
var res=Number.isFinite(10);
console.log(res);
Output
true
115
ES6
Number.isInteger()
The Number.isInteger() method determines whether the passed value is an integer.
Syntax
var res=Number.isInteger(value);
Parameter Details
Value to be tested for for being an integer.
Return Value
Returns a Boolean value, true or false.
Example
console.log(Number.isInteger(0)); // true
console.log(Number.isInteger(1)); // true
console.log(Number.isInteger(-100000)); // true
console.log(Number.isInteger(0.1)); // false
onsole.log(Number.isInteger(Infinity)); // false
console.log(Number.isInteger("10")); // false
console.log(Number.isInteger(true)); // false
console.log(Number.isInteger(false)); // false
Output
true
Number.isSafeInteger()
The Number.isSafeInteger() method determines whether the passed value is a safe
integer.
Syntax
var res=Number.isSafeInteger(value);
Parameter Details
Value to be tested for for being a safe integer.
116
ES6
Return Value
Returns a Boolean value, true or false.
Example
var res=Number.isSafeInteger(10);
console.log(res);
Output
true
Number.parseInt()
This method parses a string argument and returns an integer of the specified radix.
Syntax
Number.parseInt(string,[ radix ])
Parameters
string: value to parse
radix: integer between 2 and 36 that represents the base.
Return value
An integer representation of the string.
Example
console.log(Number.parseInt("10"));
console.log(Number.parseInt("10.23"));
Output
10
10
Number.parseFloat()
This method parses a string argument and returns a float representation of the passed
string.
117
ES6
Syntax
Number.parseFloat(string)
Parameters
string: value to parse
Return value
A float representation of the string.
Example
console.log(Number.parseFloat("10"));
console.log(Number.parseFloat("10.23"));
Output
10
10.23
toExponential()
This method returns a string representing the number object in exponential notation.
Syntax
number.toExponential( [fractionDigits] )
118
ES6
Parameter Details
fractionDigits − An integer specifying the number of digits after the decimal point.
Defaults to as many digits as necessary to specify the number.
Return Value
A string representing a Number object in exponential notation with one digit before the
decimal point, rounded to fractionDigits digits after the decimal point. If the fractionDigits
argument is omitted, the number of digits after the decimal point defaults to the number
of digits necessary to represent the value uniquely.
Example
//toExponential()
var num1=1225.30
var val= num1.toExponential();
console.log(val)
Output
1.2253e+
toFixed()
This method formats a number with a specific number of digits to the right of the decimal.
Syntax
number.toFixed( [digits] )
Parameter Details
digits − The number of digits to appear after the decimal point.
Return Value
A string representation of number that does not use exponential notation and has the
exact number of digits after the decimal place.
Example
var num3=177.234
console.log("num3.toFixed() is "+num3.toFixed())
console.log("num3.toFixed(2) is "+num3.toFixed(2))
console.log("num3.toFixed(6) is "+num3.toFixed(6))
119
ES6
Output
num3.toFixed() is 177
num3.toFixed(2) is 177.23
num3.toFixed(6) is 177.234000
toLocaleString()
This method converts a number object into a human readable string representing the
number using the locale of the environment.
Syntax
number.toLocaleString()
Return Value
Returns a human readable string representing the number using the locale of the
environment.
Example
var num = new Number(177.1234);
console.log( num.toLocaleString());
Output
177.1234
toPrecision()
This method returns a string representing the number object to the specified precision.
Syntax
number.toPrecision( [ precision ] )
Parameter Details
Return Value
Returns a string representing a Number object in fixed-point or exponential notation
rounded toprecision significant digits.
120
ES6
Example
var num = new Number(7.123456);
console.log(num.toPrecision());
console.log(num.toPrecision(1));
console.log(num.toPrecision(2));
Output
7.123456
7
7.1
toString()
This method returns a string representing the specified object. The toString() method
parses its first argument, and attempts to return a string representation in the specified
radix (base).
Syntax
number.toString( [radix] )
Parameter Details
radix − An integer between 2 and 36 specifying the base to use for representing
numeric values.
Return Value
Returns a string representing the specified Number object.
Example
var num = new Number(10);
console.log(num.toString());
console.log(num.toString(2));
console.log(num.toString(8));
121
ES6
Output
10
1010
12
valueOf()
This method returns the primitive value of the specified number object.
Syntax
number.valueOf()
Return Value
Returns the primitive value of the specified Number object.
Example
Output
10
The prefix can be written in upper or lower case. However, it is suggested to stick to the
lowercase version.
1
2
3
4
8
64
255
384
<script>
let firstName='Tutorials',lastName='Point'
let company={
firstName,
123
ES6
lastName
}
console.log(company)
console.log(company.firstName)
console.log(company.lastName)
</script>
Computed Properties
In computed properties syntax the property of object can be dynamically created from
variables. In the following example, a variable by the name suffix is used to compute
the company object.
<script>
let suffix='Name'
let company= {
['first'+suffix]:'Tutorials',
['last'+suffix]:'Point'
}
console.log(company)
console.log(company['firstName'])
console.log(company['lastName'])
</script>
In Concise method syntax we can use and declare a method directly without the use
of function keyword. This is a simplified syntax to include functions in object literals.
<script>
let firstName='Tutorials',lastName='Point'
let company={
firstName,
lastName,
getFullName(){
return this.firstName+" - "+this.lastName
}
}
console.log(company.getFullName())
console.log(company)
</script>
Tutorials - Point
{firstName: "Tutorials", lastName: "Point", getFullName: ƒ}
125
17. ES6 − Boolean ES6
The Boolean object represents two values, either "true" or "false". If the value parameter
is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has
an initial value of false.
Boolean Properties
Following is a list of the properties of Boolean object.
Property Description
Returns a reference to the Boolean function that created the
constructor
object.
The prototype property allows you to add properties and methods
prototype
to an object.
In the following sections, we will look at a few examples to illustrate the properties of
Boolean object.
constructor ()
Javascript Boolean constructor() method returns a reference to the Boolean function that
created the instance's prototype.
Use the following syntax to create a Boolean constructor() method. It returns the function
that created this object's instance.
boolean.constructor()
Example
<html>
<head>
<title>JavaScript constructor() Method</title>
</head>
<body>
<script type="text/javascript">
var bool = new Boolean( );
document.write("bool.constructor() is : " + bool.constructor);
</script>
126
ES6
</body>
</html>
Prototype
The prototype property allows you to add properties and methods to any object (Number,
Boolean, String and Date, etc.).
Note: Prototype is a global property which is available with almost all the objects.
object.prototype.name = value
Example
The following example shows how to use the prototype property to add a property to an
object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Tom");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
127
ES6
</body>
</html>
Boolean Methods
Following is a list of the methods of Boolean object and their description.
Method Description
Returns a string containing the source of the Boolean object; you
toSource()
can use this string to create an equivalent object.
Returns a string of either "true" or "false" depending upon the value
toString()
of the object.
valueOf() Returns the primitive value of the Boolean object.
In the following sections, we will take a look at a few examples to demonstrate the usage
of the Boolean methods.
toSource ()
Javascript boolean toSource() method returns a string representing the source code of
the object.
boolean.toSource()
Example
<html>
<head>
<title>JavaScript toSource() Method</title>
</head>
<body>
<script type="text/javascript">
function book(title, publisher, price)
{
128
ES6
this.title = title;
this.publisher = publisher;
this.price = price;
}
var newBook = new book("Perl","Leo Inc",200);
document.write("newBook.toSource() is : "+ newBook.toSource());
</script>
</body>
</html>
toString ()
This method returns a string of either "true" or "false" depending upon the value of the
object.
boolean.toString()
Example
<html>
<head>
<title>JavaScript toString() Method</title>
</head>
<body>
<script type="text/javascript">
var flag = new Boolean(false);
document.write( "flag.toString is : " + flag.toString() );
</script>
</body>
</html>
flag.toString is : false
129
ES6
valueOf ()
Javascript Boolean valueOf() method returns the primitive value of the specified Boolean
object.
boolean.valueOf()
Example
<html>
<head>
<title>JavaScript toString() Method</title>
</head>
<body>
<script type="text/javascript">
var flag = new Boolean(false);
document.write( "flag.valueOf is : " + flag.valueOf() );
</script>
</body>
</html>
flag.valueOf is : false
130
18. ES6 − Strings ES6
The String object lets you work with a series of characters; it wraps JavaScript’s string
primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can
call any of the helper methods of the String object on a string primitive.
The string parameter is a series of characters that has been properly encoded.
String Properties
Following is a list of the properties of String object and its description.
Property Description
constructor Returns a reference to the String function that created the object
length Returns the length of the string
prototype The prototype property allows you to add properties and methods
to an object
Constructor
A constructor returns a reference to the string function that created the instance's
prototype.
Syntax
string.constructor
Return Value
Returns the function that created this object’s instance.
Output
131
ES6
Length
This property returns the number of characters in a string.
Syntax
string.length
Output
Hello World
Length 11
Prototype
The prototype property allows you to add properties and methods to any object (Number,
Boolean, String, Date, etc.).
Note: Prototype is a global property which is available with almost all the objects.
Syntax
string.prototype
Example:Object prototype
function employee(id, name) {
this.id = id;
this.name = name;
}
var emp = new employee(123, "Smith");
employee.prototype.email = "smith@abc.com";
console.log("Employee 's Id: " + emp.id);
132
ES6
Output
Employee’s Id: 123
Employee’s name: Smith
Employee’s Email ID: smith@abc.com
String Methods
Here is a list of the methods available in String object along with their description.
Method Description
concat() Combines the text of two strings and returns a new string
Returns the index within the calling String object of the first
indexOf()
occurrence of the specified value, or -1 if not found
Returns the index within the calling String object of the last
lastIndexOf()
occurrence of the specified value, or -1 if not found
133
ES6
charAt
charAt() is a method that returns the character from the specified index.Characters in a
string are indexed from left to right. The index of the first character is 0, and the index of
the last character in a string, called stringName, is stringName.length – 1.
Syntax
string.charAt(index);
Argument Details
index − An integer between 0 and 1 less than the length of the string.
Return Value
Returns the character from the specified index.
Example
134
ES6
Output
str.charAt(0) is:T
str.charAt(1) is:h
str.charAt(2) is:i
str.charAt(3) is:s
str.charAt(4) is:
str.charAt(5) is:i
charCodeAt()
This method returns a number indicating the Unicode value of the character at the given
index. Unicode code points range from 0 to 1,114,111. The first 128 Unicode code points
are a direct match of the ASCII character encoding. charCodeAt()always returns a value
that is less than 65,536.
Syntax
string.charCodeAt(index);
Argument Details
index − An integer between 0 and 1 less than the length of the string; if
unspecified, defaults to 0.
Return Value
Returns a number indicating the Unicode value of the character at the given index. It
returns NaN if the given index is not between 0 and 1 less than the length of the string.
Example
135
ES6
Output
str.charAt(0) is:84
str.charAt(1) is:104
str.charAt(2) is:105
str.charAt(3) is:115
str.charAt(4) is:32
str.charAt(5) is:105
concat()
This method adds two or more strings and returns a new single string.
Syntax
string.concat(string2, string3[, ..., stringN]);
Argument Details
string2...stringN − These are the strings to be concatenated.
Return Value
Returns a single concatenated string.
Example
Output
str1 + str2 : This is string oneThis is string two
136
ES6
indexOf()
This method returns the index within the calling String object of the first occurrence of the
specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax
string.indexOf(searchValue[, fromIndex])
Argument Details
searchValue − A string representing the value to search for.
fromIndex − The location within the calling string to start the search from. It can
be any integer between 0 and the length of the string. The default value is 0.
Return Value
Returns the index of the found occurrence, otherwise -1 if not found.
Example
Output
indexOf found String :8
indexOf found String :15
lastIndexOf()
This method returns the index within the calling String object of the last occurrence of the
specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax
string.lastIndexOf(searchValue[, fromIndex])
137
ES6
Argument Details
fromIndex − The location within the calling string to start the search from. It can
be any integer between 0 and the length of the string. The default value is 0.
Return Value
Returns the index of the last found occurrence, otherwise -1 if not found.
Example
var str1 = new String( "This is string one and again string" );
var index = str1.lastIndexOf( "string" );
console.log("lastIndexOf found String :" + index );
Output
lastIndexOf found String :29
localeCompare()
This method returns a number indicating whether a reference string comes before or after
or is the same as the given string in sorted order.
Syntax
string.localeCompare( param )
Argument Details
param − A string to be compared with string object.
Return Value
0 − If the string matches 100%.
1 − no match, and the parameter value comes before the string object's value in
the locale sort order
138
ES6
Example
Output
localeCompare first :0
replace()
This method finds a match between a regular expression and a string, and replaces the
matched substring with a new substring.
The replacement string can include the following special replacement patterns –
Pattern Inserts
$$ Inserts a "$".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n or $nn Where n or nn are decimal digits, inserts the nth parenthesized submatch
string, provided the first argument was a RegExp object.
Syntax
string.replace(regexp/substr, newSubStr/function[, flags]);
Argument Details
regexp − A RegExp object. The match is replaced by the return value of parameter
#2.
newSubStr − The String that replaces the substring received from parameter #1.
Return Value
It simply returns a new changed string.
Example
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
console.log(newstr)
Output
oranges are round, and oranges are juicy.
Example
var re = /(\w+)\s(\w+)/;
var str = "zara ali";
var newstr = str.replace(re, "$2, $1");
console.log(newstr);
Output
ali, zara
search()
This method executes the search for a match between a regular expression and this String
object.
Syntax
string.search(regexp);
Argument Details
regexp − A regular expression object. If a non-RegExp object obj is passed, it is implicitly
converted to a RegExp by using new RegExp(obj).
Return Value
If successful, the search returns the index of the regular expression inside the string.
Otherwise, it returns -1.
140
ES6
Example
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
if ( str.search(re) == -1 )
{
console.log("Does not contain Apples" );
}
else
{
console.log("Contains Apples" );
}
Output
Contains Apples
slice()
This method extracts a section of a string and returns a new string.
Syntax
string.slice( beginslice [, endSlice] );
Argument Details
beginSlice − The zero-based index at which to begin extraction.
Return Value
If successful, slice returns the index of the regular expression inside the string. Otherwise,
it returns -1.
Example
var str = "Apples are round, and apples are juicy.";
var sliced = str.slice(3, -2);
141
ES6
console.log(sliced);
Output
les are round, and apples are juic
split()
This method splits a String object into an array of strings by separating the string into
substrings.
Syntax
string.split([separator][, limit]);
Argument Details
separator − Specifies the character to use for separating the string. Ifseparator is
omitted, the array returned contains one element consisting of the entire string.
Return Value
The split method returns the new array. Also, when the string is empty, split returns an
array containing one empty string, rather than an empty array.
Example
var str = "Apples are round, and apples are juicy.";
var splitted = str.split(" ", 3);
console.log(splitted)
Output
[ 'Apples', 'are', 'round,' ]
substr()
This method returns the characters in a string beginning at the specified location through
the specified number of characters.
Syntax
string.substr(start[, length]);
142
ES6
Argument Details
start − Location at which to start extracting characters (an integer between 0 and
one less than the length of the string).
Note − If start is negative, then substr uses it as a character index from the end of the
string.
Return Value
The substr() method returns the new sub-string based on given parameters.
Example
var str = "Apples are round, and apples are juicy.";
console.log("(1,2): " + str.substr(1,2));
console.log("(-2,2): " + str.substr(-2,2));
console.log("(1): " + str.substr(1));
console.log("(-20, 2): " + str.substr(-20,2));
console.log("(20, 2): " + str.substr(20,2));
Output
(1,2): pp
(-2,2): y.
(1): pples are round, and apples are juicy.
(-20, 2): nd
(20, 2): d
substring()
This method returns a subset of a String object.
Syntax
string.substring(indexA, [indexB])
Argument Details
indexA − An integer between 0 and one less than the length of the string.
143
ES6
Return Value
The substring method returns the new sub-string based on given parameters.
Example
var str = "Apples are round, and apples are juicy.";
console.log("(1,2): " + str.substring(1,2));
console.log("(0,10): " + str.substring(0, 10));
console.log("(5): " + str.substring(5));
Output
(1,2): p
(0,10): Apples are
(5): s are round, and apples are juicy.
toLocaleLowerCase()
This method is used to convert the characters within a string to lowercase while respecting
the current locale. For most languages, it returns the same output as toLowerCase.
Syntax
string.toLocaleLowerCase( )
Return Value
Returns a string in lowercase with the current locale.
Example
var str = "Apples are round, and Apples are Juicy.";
console.log(str.toLocaleLowerCase( ));
Output
apples are round, and apples are juicy.
144
ES6
toLowerCase()
This method returns the calling string value converted to lowercase.
Syntax
string.toLowerCase( )
Return Value
Returns the calling string value converted to lowercase.
Example
var str = "Apples are round, and Apples are Juicy.";
console.log(str.toLowerCase( ))
Output
apples are round, and apples are juicy.
toString()
This method returns a string representing the specified object.
Syntax
string.toString( )
Return Value
Returns a string representing the specified object.
Example
var str = "Apples are round, and Apples are Juicy.";
console.log(str.toString( ));
Output
Apples are round, and Apples are Juicy.
145
ES6
toUpperCase()
This method returns the calling string value converted to uppercase.
Syntax
string.toUpperCase( )
Return Value
Returns a string representing the specified object.
Example
var str = "Apples are round, and Apples are Juicy.";
console.log(str.toUpperCase( ));
Output
APPLES ARE ROUND, AND APPLES ARE JUICY.
valueOf()
This method returns the primitive value of a String object.
Syntax
string.valueOf( )
Return Value
Returns the primitive value of a String object.
Example
var str = new String("Hello world");
console.log(str.valueOf( ));
146
19. ES6 — Symbol ES6
Introduction to Symbol
ES6 introduces a new primitive type called Symbol. They are helpful to implement
metaprogramming in JavaScript programs.
Syntax
const mySymbol = Symbol()
const mySymbol = Symbol(stringDescription)
A symbol is just a piece of memory in which you can store some data. Each symbol will
point to a different memory location. Values returned by a Symbol() constructor are
unique and immutable.
Example
Let us understand this through an example. Initially, we created two symbols without
description followed by symbols with same description. In both the cases the equality
operator will return false when the symbols are compared.
<script>
const s1 = Symbol();
const s2 = Symbol();
console.log(typeof s1)
console.log(s1===s2)
const s3 = Symbol("hello");//description
const s4 = Symbol("hello");
console.log(s3)
console.log(s4)
console.log(s3==s4)
</script>
symbol
false
147
ES6
Symbol(hello)
Symbol(hello)
false
Sharing Symbols
ES6 provides a global symbols registry, that allows programmers to share Symbols
globally. We can add Symbols to registry and reuse them later. In this way, symbols can
be shared.
Symbol.for()
This function creates a symbol and adds to registry. If the symbol is already present in the
registry it will return the same; else a new symbol is created in the global symbol registry.
Syntax
Symbol.for(key)
Example
The following example shows the difference between Symbol() and Symbol.for()
<script>
const userId = Symbol.for('userId') // creates a new Symbol in registry
const user_Id = Symbol.for('userId') // reuses already created Symbol
console.log(userId == user_Id)
148
ES6
true
false
Symbol.keyFor
This method retrieves a shared symbol key from the global symbol registry for the given
symbol.
Syntax
The syntax for Symbol.keyFor is mentioned below where, sym is the symbol to find a key
for.
Symbol.keyFor(sym)
Example
<script>
const user_Id = Symbol.for('userId') // creates a new Symbol in registry
console.log(Symbol.keyFor(user_Id)) // returns the key of a symbol in
registry
userId
undefined
149
ES6
Example
<script>
const COLOR = Symbol()
const MODEL = Symbol()
const MAKE = Symbol()
class Bike {
constructor(color ,make,model){
this[COLOR] = color;
this[MAKE] = make;
this[MODEL] = model;
}
150
20. ES6 − New String Methods ES6
Method Description
startsWith
The method determines if a string starts with the specified character.
Syntax
str.startsWith(searchString[, position])
Parameters
searchString: The characters to be searched for at the start of this string.
Position: The position in this string at which to begin searching for searchString;
defaults to 0
Return Value
true if the string begins with the characters of the search string; otherwise, false.
Example
var str = 'hello world!!!';
console.log(str.startsWith('hello'));
151
ES6
Output
true
endsWith
This function determines whether a string ends with the characters of another string.
Syntax
str.endsWith(matchstring[, position])
Parameters
matchstring: The characters that the string must end with. It is case sensitive.
Position: The position to match the matchstring. This parameter is optional.
Return Value
true if the string ends with the characters of the match string; otherwise, false.
Example
var str = 'Hello World !!! ';
console.log(str.endsWith('Hello'));
console.log(str.endsWith('Hello',5));
Output
false
true
includes()
The method determines if a string is a substring of the given string.
Syntax
str.includes(searchString[, position])
152
ES6
Parameters
searchString : The substring to search for.
Position: The position in this string at which to begin searching for searchString;
defaults to 0
Return Value
true if the string contains the substring ; otherwise, false.
Example
var str = 'Hello World';
console.log(str.includes('hell'))
console.log(str.includes('Hell'));
console.log(str.includes('or'));
console.log(str.includes('or',1))
Output
false
true
true
true
repeat()
This function repeats the specified string for a specified number of times.
Syntax
str.repeat(count)
Parameters
Count: number of times the string should be repeated.
Return Value
Returns a new string.
153
ES6
Example
var myBook = new String("Perl");
console.log(myBook.repeat(2));
PerlPerl
Template Literals
Template literals are string literals that allow embedded expressions. Templatestrings
use back-ticks (``) rather than the single or double quotes. A template string could thus
be written as:
Example 1
var name = "Brendan";
console.log('Hello, ${name}!');
Hello, Brendan!
154
ES6
Example
var multiLine = '
This is
a string
with multiple
lines';
console.log(multiLine)
This is
a string
with multiple
line
String.raw()
ES6 includes the tag function String.raw for raw strings, where backslashes have no special
meaning. String.raw enables us to write the backslash as we would in a regular
expression literal. Consider the following example.
Hello
World
155
ES6
Hello \n World
Tagged Templates
A tag is a function which can interpret and process a template literal. A tag appears in
front of the template literal. Syntax is shown below.
Syntax
let output_fromTag = tagFunction `Template literal with ${variable1} ,
${variable2}`
function tagFunction(literals,...variable_values){
//process
return "some result"
}
Example
Following Example defines a tag function myTagFn(). It displays the parameters passed
to it. After displaying it returns Done to the caller.
<script>
function myTagFn(literals,...values){
return "Done"
}
let company = `TutorialsPoint`
let company_location = `Mumbai`
156
ES6
console.log(result)
</script>
//literal
literal values are
Hello this is
from
//values
variable values are
TutorialsPoint
Mumbai
Done
Example
The below tag function takes a template literal and converts it to upper case as shown
below:
<script>
function convertToUpperTagFn(literals, ...values) {
return result.toUpperCase();
}
let company = `TutorialsPoint`
157
ES6
console.log(result)
</script>
String.fromCodePoint()
The static String.fromCodePoint() method returns a string created by using the specified
sequence of unicode code points. The function throws a RangeError if an invalid code point
is passed.
console.log(String.fromCodePoint(42))
console.log(String.fromCodePoint(65, 90))
*
AZ
158
21. ES6 − Arrays ES6
Variables are scalar in nature. In other words, a variable declaration can only
contain a single at a time. This means that to store n values in a program, n
variable declarations will be needed. Hence, the use of variables is not feasible
when one needs to store a larger collection of values.
Features of an Array
An array declaration allocates sequential memory blocks.
Arrays are static. This means that an array once initialized cannot be resized.
Arrays too, like variables, should be declared before they are used.
159
ES6
For example, a declaration like: var numlist = [2,4,6,8] will create an array as shown
in the following figure.
array_name[subscript]
1
2
1
2
3
3
160
ES6
Array Object
An array can also be created using the Array object. The Array constructor can be passed
as -
Example
var arr_names=new Array(4)
for(var i=0;i<arr_names.length;i++)
{
arr_names[i]=i * 2
console.log(arr_names[i])
}
0
2
4
6
Mary
Tom
Jack
Jill
161
ES6
Array Methods
Following is the list of the methods of the Array object along with their description.
Method Description
Creates a new array with all of the elements of this array for which
filter()
the provided filtering function returns true
Returns the first (least) index of an element within the array equal
indexOf()
to the specified value, or -1 if none is found
pop() Removes the last element from an array and returns that element
Adds one or more elements to the end of an array and returns the
push()
new length of the array
reverse() Reverses the order of the elements of an array -- the first becomes
the last, and the last becomes the first
162
ES6
shift() Removes the first element from an array and returns that element
Adds one or more elements to the front of an array and returns the
unshift()
new length of the array
concat()
concat() method returns a new array comprised of this array joined with two or more
arrays.
Syntax
array.concat(value1, value2, ..., valueN);
Parameters
valueN − Arrays and/or values to concatenate to the resulting array.
Return Value
Returns a new array.
Example
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
163
ES6
Output
alphaNumeric : a,b,c,1,2,3
every()
every method tests whether all the elements in an array passes the test implemented by
the provided function
Syntax
array.every(callback[, thisObject]);
Parameter Details
Return Value
Returns true if every element in this array satisfies the provided testing function.
Example
function isBigEnough(element, index, array) {
return (element >= 10);
}
Output
Test Value : false
filter()
filter() method creates a new array with all elements that pass the test implemented by
the provided function.
164
ES6
Syntax
array.filter(callback[, thisObject]);
Parameter Details
Return Value
Returns created array.
Example
function isBigEnough(element, index, array) {
return (element >= 10);
}
Output
Test Value :12,130,44
forEach()
forEach() method calls a function for each element in the array
Syntax
array.forEach(callback[, thisObject]);
Parameter Details
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
Return Value
Returns created array.
165
ES6
Example:forEach()
var nums=new Array(12,13,14,15)
nums.forEach(function(val,index){
console.log(val)
})
nums.forEach(function(val,index){
console.log(val)
})
indexOf()
indexOf() method returns the first index at which a given element can be found in the
array, or -1 if it is not present.
Syntax
166
ES6
array.indexOf(searchElement[, fromIndex]);
Parameter Details
searchElement − Element to locate in the array.
fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole
array will be searched. If the index is greater than or equal to the length of the
array, -1 is returned.
Return Value
Returns the index of the found element.
Example
var index = [12, 5, 8, 130, 44].indexOf(8);
console.log("index is : " + index );
Output
index is : 2
join()
join() method joins all the elements of an array into a string.
Syntax
array.join(separator);
Parameter Details
separator − Specifies a string to separate each element of the array. If omitted,
the array elements are separated with a comma.
Return Value
Returns a string after joining all the array elements.
Example
var arr = new Array("First","Second","Third");
167
ES6
Output
str : First,Second,Third
str : First, Second, Third
str : First + Second + Third
lastIndexOf()
lastIndexOf() method returns the last index at which a given element can be found in the
array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.
Syntax
array.lastIndexOf(searchElement[, fromIndex]);
Parameter Details
searchElement − Element to locate in the array.
Return Value
Returns the index of the found element from the last.
Example
var index = [12, 5, 8, 130, 44].lastIndexOf(8);
console.log("index is : " + index );
168
ES6
Output
index is : 3
map()
map() method creates a new array with the results of calling a provided function on every
element in this array.
Syntax
array.map(callback[, thisObject]);
Parameter Details
callback − Function that produces an element of the new Array from an element
of the current one.
Return Value
Returns the created array.
Example
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
console.log("roots is : " + roots );
Output
roots is : 1,2,3
pop()
pop() method removes the last element from an array and returns that element.
Syntax
169
ES6
array.pop();
Return Value
Returns the removed element from the array.
Example
var numbers = [1, 4, 9];
Output
element is : 9
element is : 4
push()
push() method appends the given element(s) in the last of the array and returns the length
of the new array.
Syntax
array.push(element1, ..., elementN);
Parameter Details
element1, ..., elementN: The elements to add to the end of the array.
Return Value
Returns the length of the new array.
Example
var numbers = new Array(1, 4, 9);
170
ES6
Output
new numbers is : 1,4,9,10
new numbers is : 1,4,9,10,20
reduce()
reduce() method applies a function simultaneously against two values of the array (from
left-to-right) as to reduce it to a single value.
Syntax
array.reduce(callback[, initialValue]);
Parameter Details
callback − Function to execute on each value in the array.
initialValue − Object to use as the first argument to the first call of the callback.
Return Value
Returns the reduced single value of the array.
Example
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
console.log("total is : " + total );
Output
total is : 6
reduceRight()
reduceRight() method applies a function simultaneously against two values of the array
(from right-to-left) as to reduce it to a single value
Syntax
171
ES6
array.reduceRight(callback[, initialValue]);
Parameter Details
callback − Function to execute on each value in the array.
initialValue − Object to use as the first argument to the first call of the callback.
Return Value
Returns the reduced right single value of the array.
Example
var total = [0, 1, 2, 3].reduceRight(function(a, b){ return a + b; });
console.log("total is : " + total );
Output
total is : 6
reverse()
reverse() method reverses the element of an array. The first array element becomes the
last and the last becomes the first.
Syntax
array.reverse();
Return Value
Returns the reversed single value of the array.
Example
var arr = [0, 1, 2, 3].reverse();
console.log("Reversed array is : " + arr );
Output
Reversed array is : 3,2,1,0
172
ES6
shift()
shift()method removes the first element from an array and returns that element.
Syntax
array.shift();
Return Value
Returns the removed single value of the array
Example
var arr = [10, 1, 2, 3].shift();
console.log("Shifted value is : " + arr );
Output
Shifted value is : 10
slice()
slice() method extracts a section of an array and returns a new array.
Syntax
array.slice( begin [,end] );
Parameter Details
begin − Zero-based index at which to begin extraction. As a negative index, start
indicates an offset from the end of the sequence.
Return Value
Returns the extracted array based on the passed parameters.
Example
var arr = ["orange", "mango", "banana", "sugar", "tea"];
console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) );
173
ES6
Output
arr.slice( 1, 2) : mango
arr.slice( 1, 3) : mango,banana
some()
some() method tests whether some element in the array passes the test implemented by
the provided function.
Syntax
array.some(callback[, thisObject]);
Parameter Details
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
Return Value
If some element passes the test, then it returns true, otherwise false.
Example
function isBigEnough(element, index, array)
{
return (element >= 10);
Output
Returned value is : false
174
ES6
sort()
sort() method sorts the elements of an array.
Syntax
array.sort( compareFunction );
Parameter Details
compareFunction − Specifies a function that defines the sort order. If omitted, the array
is sorted lexicographically.
Return Value
Returns a sorted array.
Example
var arr = new Array("orange", "mango", "banana", "sugar");
var sorted = arr.sort();
console.log("Returned string is : " + sorted );
Output
Returned string is : banana,mango,orange,sugar
splice()
splice() method changes the content of an array, adding new elements while removing
old elements.
Syntax
array.splice(index, howMany, [element1][, ..., elementN]);
Parameter Details
index − Index at which to start changing the array.
element1, ..., elementN − The elements to add to the array. If you don't
specify any elements, splice simply removes the elements from the array.
175
ES6
Return Value
Returns the extracted array based on the passed parameters.
Example
var arr = ["orange", "mango", "banana", "sugar", "tea"];
Output
After adding 1: orange,mango,water,banana,sugar,tea
removed is:
After adding 1: orange,mango,water,sugar,tea
removed is: banana
toString()
toString() method returns a string representing the source code of the specified array
and its elements.
Syntax
array.toString();
Return Value
Returns a string representing the array.
Example
176
ES6
Output
Returned string is : orange,mango,banana,sugar
unshift()
unshift() method adds one or more elements to the beginning of an array and returns
the new length of the array.
Syntax
array.unshift( element1, ..., elementN );
Parameter Details
element1, ..., elementN − The elements to add to the front of the array.
Return Value
Returns the length of the new array. It returns undefined in IE browser.
Example
var arr = new Array("orange", "mango", "banana", "sugar");
var length = arr.unshift("water");
console.log("Returned array is : " + arr );
console.log("Length of the array is : " + length );
Output
Returned array is : water,orange,mango,banana,sugar
Length of the array is : 5
Array.prototype.find
177
ES6
find lets you iterate through an array and get the first element back that causes the given
callback function to return true. Once an element has been found, the function immediately
returns. It’s an efficient way to get at just the first item that matches a given condition.
Example
var numbers = [1, 2, 3];
var oddNumber = numbers.find((x) => x % 2 == 1);
console.log(oddNumber); // 1
Note: The ES5 filter() and the ES6 find() are not synonymous. Filter always returns an
array of matches (and will return multiple matches), find always returns the actual
element.
Array.prototype.findIndex
findIndex behaves similar to find, but instead of returning the element that matched, it
returns the index of that element.
The above example will return the index of the value 1 (0) as output.
Array.prototype.entries
entries is a function that returns an Array Iterator that can be used to loop through the
array’s keys and values. Entries will return an array of arrays, where each child array is
an array of [index, value].
[0,1]
[1.2]
178
ES6
[2,3]
Alternatively, we can also use the spread operator to get back an array of the entries in
one go.
[[0,1],[1,2],[2,3]]
Array.from
Array.from() enables the creation of a new array from an array like object. The basic
functionality of Array.from() is to convert two kinds of values to Arrays:
Array-like values
Iterable values like Set and Map
Example
"use strict"
for (let i of Array.from('hello'))
{
console.log(i)
}
h
e
l
l
o
Array.prototype.keys()
This function returns the array indexes.
179
ES6
Example
console.log(Array.from(['a', 'b'].keys()))
[ 0, 1 ]
"use strict"
var nums=[1001,1002,1003,1004]
for(let j in nums)
{
console.log(nums[j])
}
The loop performs an index-based array traversal. The following output is displayed on
successful execution of the above code.
1001
1002
1003
1004
Arrays in JavaScript
JavaScript supports the following concepts about Arrays:
Concept Description
Passing arrays to functions You can pass to the function a pointer to an array by
specifying the array's name without an index
Multidimensional Arrays
180
ES6
An array element can reference another array for its value. Such arrays are called as
multi-dimensionalarrays. ES6 supports the concept of multi-dimensional arrays. The
simplest form of a multi-dimensional array is a two-dimensional array.
Example
var multi=[[1,2,3],[23,24,25]]
console.log(multi[0][0])
console.log(multi[0][1])
console.log(multi[0][2])
console.log(multi[1][0])
console.log(multi[1][1])
console.log(multi[1][2])
The above example initially declares an array with 2 elements. Each of these elements
refer to another array having 3 elements. Following is the pictorial representation of the
above array.
While referring to an array element here, the subscript of the initial array element must
be followed by the subscript of the referenced array element. This is illustrated in the
above code.
181
ES6
1
2
3
23
24
25
Mary
Tom
Jack
Jill
182
ES6
Mary
Tom
Jack
Jill
Array De-structuring
Destructuring refers to extracting individual values from an array or an object into
distinct variables. Consider a scenario where the values of an array need to be assigned
to individual variables. The traditional way of doing this is given below:
var a= array1[0]
var b= array1[1]
var c= array1[2]
Syntax
//destructuring an array
let [variable1,variable2]=[item1,item2]
//destructuring an object
Example
<script>
console.log(n1)
console.log(n2)
console.log(n3);
183
ES6
//swapping
let first=10,second=20;
[second,first] = [first,second]
console.log("second is ",second) //10
console.log("first is ",first) //20
</script>
Mohtashim
Kannan
Kiran
Mumbai
["Hyderabad", "Chennai"]
Mohtashim
Kannan
second is 10
first is 20
184
22. ES6 − Date ES6
The Date object is a datatype built into the JavaScript language. Date objects are created
with the new Date () as shown in the following syntax.
Once a Date object is created, a number of methods allow you to operate on it. Most
methods simply allow you to get and set the year, month, day, hour, minute, second, and
millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and
time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a
range of plus or minus 273,785 years, so JavaScript can represent date and time till the
year 275755.
You can use any of the following syntax to create a Date object using Date ()
constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Date Properties
Here is a list of the properties of the Date object along with their description.
Property Description
Constructor
Javascript date constructor property returns a reference to the array function that created
the instance's prototype.
Syntax
date.constructor
185
ES6
Return value
Returns the function that created this object's instance.
Example: constructor
var dt = new Date();
console.log("dt.constructor is : " + dt.constructor);
prototype
The prototype property allows you to add properties and methods to any object (Number,
Boolean, String, Date, etc.). Note: Prototype is a global property which is available with
almost all the objects.
Syntax
object.prototype.name = value
Example:Date.prototype
var myBook = new book("Perl", "Mohtashim");
book.prototype.price = null;
myBook.price = 100;
console.log("Book title is : " + myBook.title + "<br>");
console.log("Book author is : " + myBook.author + "<br>");
console.log("Book price is : " + myBook.price + "<br>");
186
ES6
Date Methods
Following is a list of different date methods along with the description.
Method Description
setDate() Sets the day of the month for a specified date according to
the local time
setFullYear() Sets the full year for a specified date according to the local
time
setHours() Sets the hours for a specified date according to the local time
setMilliseconds()
187
ES6
setMonth() Sets the month for a specified date according to the local time
setUTCMonth() Sets the month for a specified date according to the universal
time
toLocaleDateString() Returns the "date" portion of the Date as a string, using the
current locale's conventions
toLocaleTimeString() Returns the "time" portion of the Date as a string, using the
current locale's conventions
188
ES6
Date()
Javascript Date() method returns today's date and time and does not need any object to
be called.
Syntax
Date()
Return Value
Returns today's date and time.
Example
var dt = Date();
console.log("Current Date ",dt);
Output
Current Date Tue Sep 20 2016 22:24:31 GMT+0530 (India Standard Time)
getDate()
Javascript date getDate() method returns the day of the month for the specified date
according to local time. The value returned by getDate is an integer between 1 and 31.
Syntax
Date.getDate()
Return Value
Returns today's date and time.
189
ES6
Example
var dt = new Date("December 25, 1995 23:15:00");
console.log("getDate() : " + dt.getDate() );
Output
getDate() : 25
getDay()
Javascript date getDay() method returns the day of the week for the specified date
according to local time. The value returned by getDay is an integer corresponding to the
day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
Syntax
Date.getDay()
Return Value
Returns the day of the week for the specified date according to local time.
Example
var dt = new Date("December 25, 1995 23:15:00");
console.log("getDay() : " + dt.getDay() );
Output
getDay() : 1
getFullYear()
Javascript date getFullYear() method returns the year of the specified date according to
local time. The value returned by getFullYear is an absolute number. For dates between
the years 1000 and 9999, getFullYear returns a four-digit number, for example, 2008.
Syntax
Date.getFullYear()
Return Value
Returns the year of the specified date according to local time.
190
ES6
Example
var dt = new Date("December 25, 1995 23:15:00");
console.log("getFullYear() : " + dt.getFullYear() );
Output
getFullYear() : 1995
getHours()
Javascript Date getHours() method returns the hour in the specified date according to local
time. The value returned by getHours is an integer between 0 and 23.
Syntax
Date.getHours()
Return Value
Returns the hour in the specified date according to local time.
Example
var dt = new Date("December 25, 1995 23:15:00");
console.log("getHours() : " + dt.getHours() );
Output
getHours() : 23
getMilliseconds()
Javascript date getMilliseconds() method returns the milliseconds in the specified date
according to local time. The value returned by getMilliseconds is a number between 0 and
999.
Syntax
Date.getMilliseconds ()
Return Value
Returns the milliseconds in the specified date according to local time.
Example
191
ES6
Output
getMilliseconds() : 0
getMinutes()
Javascript date getMinutes() method returns the minutes in the specified date according
to local time. The value returned by getMinutes is an integer between 0 and 59.
Syntax
Date.getMinutes ()
Return Value
Returns the minutes in the specified date according to local time.
Example
var dt = new Date("December 25, 1995 23:15:00");
console.log("getMinutes() : " + dt.getMinutes() );
Output
getMinutes() : 15
getMonth()
Javascript date getMonth() method returns the month in the specified date according to
local time. The value returned by getMonth is an integer between 0 and 11. 0 corresponds
to January, 1 to February, and so on.
Syntax
Date.getMonth ()
Return Value
Returns the Month in the specified date according to local time.
Example
var dt = new Date("December 25, 1995 23:15:00");
192
ES6
Output
getMonth() : 11
getSeconds()
Javascript date getSeconds() method returns the seconds in the specified date according
to local time. The value returned by getSeconds is an integer between 0 and 59.
Syntax
Date.getSeconds ()
Return Value
Returns the seconds in the specified date according to local time.
Example
var dt = new Date("December 25, 1995 23:15:00");
console.log("getSeconds() : " + dt.getSeconds() );
Output
getSeconds() : 0
getTime()
Javascript date getTime() method returns the numeric value corresponding to the time for
the specified date according to universal time. The value returned by the getTime method
is the number of milliseconds since 1 January 1970 00:00:00.
You can use this method to help assign a date and time to another Date object.
Syntax
Date.getTime ()
Return Value
Returns the numeric value corresponding to the time for the specified date according to
universal time.
Example
193
ES6
Output
getTime() : 819913500000
getTimezoneOffset()
Javascript date getTimezoneOffset() method returns the time-zone offset in minutes for
the current locale. The time-zone offset is the minutes in difference, the Greenwich Mean
Time (GMT) is relative to your local time.
For example, if your time zone is GMT+10, -600 will be returned. Daylight savings time
prevents this value from being a constant.
Syntax
Date.getTimezoneOffset()
Return Value
Returns the time-zone offset in minutes for the current locale.
Example
var dt = new Date("December 25, 1995 23:15:00");
console.log("getTimezoneoffset() : " + dt.getTimezoneOffset() );
Output
getTimezoneoffset() : -330
getUTCDate()
Javascript date getUTCDate() method returns the day of the month in the specified date
according to universal time. The value returned by getUTCDate is an integer between 1
and 31.
Syntax
Date.getUTCDate ()
Return Value
Returns the day of the month in the specified date according to universal time.
194
ES6
Example
var dt = new Date( "December 25, 1995 23:15:20" );
console.log("getUTCDate() : " + dt.getUTCDate() );
Output
getUTCDate() : 25
getUTCDay()
Javascript date getUTCDay() method returns the day of the week in the specified date
according to universal time. The value returned by getUTCDay is an integer corresponding
to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
Syntax
Date.getUTCDay ()
Return Value
Returns the day of the week in the specified date according to universal time.
Example
var dt = new Date( "December 25, 1995 23:15:20" );
console.log("getUTCDay() : " + dt.getUTCDay() );
Output
getUTCDay() : 1
getUTCFullYear()
Javascript date getUTCFullYear() method returns the year in the specified date according
to universal time. The value returned by getUTCFullYear is an absolute number that is
compliant with year-2000, for example, 2008.
Syntax
Date.getUTCFullYear ()
Return Value
Returns the year in the specified date according to universal time.
195
ES6
Example
var dt = new Date( "December 25, 1995 23:15:20" );
console.log("getUTCFullYear() : " + dt.getUTCFullYear() );
Output
getUTCFullYear() : 1995
getUTCHours()
Javascript date getUTCHours() method returns the hours in the specified date according
to universal time. The value returned by getUTCHours is an integer between 0 and 23.
Syntax
Date.getUTCHours ()
Return Value
Returns the hours in the specified date according to universal time.
Example
var dt = new Date( "December 25, 1995 23:15:20" );
console.log("getUTCHours() : " + dt.getUTCHours() );
Output
getUTCHours() : 17
getUTCMilliseconds()
Javascript date getUTCMilliseconds() method returns the milliseconds in the specified date
according to universal time. The value returned by getUTCMilliseconds is an integer
between 0 and 999.
Syntax
Date.getUTCMilliseconds ()
Return Value
Returns the milliseconds in the specified date according to universal time.
196
ES6
Example
var dt = new Date( "December 25, 1995 23:15:20" );
console.log("getUTCMilliseconds() : " + dt.getUTCMilliseconds())
Output
getUTCMilliseconds() : 0
getUTCMinutes()
Javascript date getUTCMinutes() method returns the minutes in the specified date
according to universal time. The value returned by getUTCMinutes is an integer between
0 and 59.
Syntax
Date.getUTCMinutes ()
Return Value
Returns the minutes in the specified date according to universal time.
Example
var dt = new Date( "December 25, 1995 23:15:20" );
console.log("getUTCMinutes() : " + dt.getUTCMinutes() );
Output
getUTCMinutes() : 45
getUTCMonth()
Javascript date getUTCMonth() method returns the month in the specified date according
to universal time. The value returned by getUTCMonth is an integer between 0 and 11
corresponding to the month. 0 for January, 1 for February, 2 for March, and so on.
Syntax
Date.getUTCMonth ()
Return Value
Returns the month in the specified date according to universal time.
197
ES6
Example
var dt = new Date( "December 25, 1995 23:15:20" );
console.log("getUTCMonth() : " + dt.getUTCMonth() );
Output
getUTCMonth() : 11
getUTCSeconds()
Javascript date getUTCSeconds() method returns the seconds in the specified date
according to universal time. The value returned by getUTCSeconds is an integer between
0 and 59.
Syntax
Date.getUTCSeconds ()
Return Value
Returns the seconds in the specified date according to universal time.
Example
var dt = new Date( "December 25, 1995 23:15:20" );
console.log("getUTCSeconds() : " + dt.getUTCSeconds() );
getUTCSeconds() : 20
setDate()
Javascript date setDate() method sets the day of the month for a specified date according
to local time.
Syntax
Date.setDate( dayValue )
Parameter
dayValue − An integer from 1 to 31, representing the day of the month.
Example
198
ES6
Output
Sun Aug 24 2008 23:30:00 GMT+0530 (India Standard Time)
setFullYear()
Javascript date setFullYear() method sets the full year for a specified date according to
local time.
Parameter
yearValue − An integer specifying the numeric value of the year, for example,
2008.
dayValue − An integer between 1 and 31 representing the day of the month. If you
specify the dayValue parameter, you must also specify the monthValue.
If you do not specify the monthValue and dayValue parameters, the values returned
from the getMonth and getDate methods are used.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setFullYear( 2000 );
console.log( dt )
Output
Mon Aug 28 2000 23:30:00 GMT+0530 (India Standard Time)
setHours()
Javascript date setHours() method sets the hours for a specified date according to local
time..
Syntax
199
ES6
Parameter
hoursValue − An integer between 0 and 23, representing the hour.
If you do not specify the minutesValue, secondsValue, and msValue parameters, the
values returned from the getUTCMinutes, getUTCSeconds, and getMilliseconds methods
are used.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setHours(02);
console.log(dt);
Output
Thu Aug 28 2008 02:30:00 GMT+0000 (UTC)
setMilliseconds()
Javascript date setMilliseconds() method sets the milliseconds for a specified date
according to local time.
Syntax
Date.setMilliseconds(millisecondsValue)
Parameter
millisecondsValue − A number between 0 and 999, representing the
milliseconds.
If you specify a number outside the expected range, the date information in the Date
object is updated accordingly. For example, if you specify 1010, the number of seconds is
incremented by 1, and 10 is used for the milliseconds.
Example
200
ES6
Output
Thu Aug 28 2008 23:30:01 GMT+0530 (India Standard Time)
setMinutes()
Javascript date setMinutes() method sets the minutes for a specified date according to
local time.
Syntax
Date.setMinutes(minutesValue[, secondsValue[, msValue]])
Parameter
minutesValue − An integer between 0 and 59, representing the minutes.
If you do not specify the secondsValue and msValue parameters, the values returned from
getSeconds and getMilliseconds methods are used.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setMinutes( 45 );
console.log( dt );
Output
Thu Aug 28 2008 23:45:00 GMT+0530 (India Standard Time)
setMonth()
Javascript date setMonth() method sets the month for a specified date according to local
time.
201
ES6
Syntax
Date.setMonth(monthValue[, dayValue])
Parameter
monthValue − An integer between 0 and 11 (representing the months January
through December).
If you do not specify the dayValue parameter, the value returned from the getDate method
is used. If a parameter you specify is outside of the expected range, setMonth attempts
to update the date information in the Date object accordingly. For example, if you use 15
for monthValue, the year will be incremented by 1 (year + 1), and 3 will be used for
month.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setMonth( 2 );
console.log( dt );
Output
Fri Mar 28 2008 23:30:00 GMT+0530 (India Standard Time)
setSeconds()
Javascript date setSeconds() method sets the seconds for a specified date according to
local time
Syntax
Date.setSeconds(secondsValue[, msValue])
Parameter
secondsValue − An integer between 0 and 59.
202
ES6
If you do not specify the msValue parameter, the value returned from the getMilliseconds
method is used. If a parameter you specify is outside of the expected range, setSeconds
attempts to update the date information in the Date object accordingly. For example, if
you use 100 for secondsValue, the minutes stored in the Date object will be incremented
by 1, and 40 will be used for seconds.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setSeconds( 80 );
console.log( dt );
Output
Thu Aug 28 2008 23:31:20 GMT+0530 (India Standard Time)
setTime()
Javascript date setTime()method sets the Date object to the time represented by a number
of milliseconds since January 1, 1970, 00:00:00 UTC.
Syntax
Date.setTime(timeValue)
Parameter
timeValue − An integer representing the number of milliseconds since 1 January
1970, 00:00:00 UTC.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setTime( 5000000 );
console.log( dt );
Output
Thu Jan 01 1970 06:53:20 GMT+0530 (India Standard Time)
203
ES6
setUTCDate()
Javascript date setUTCDate() method sets the day of the month for a specified date
according to universal time.
Syntax
Date.setUTCDate(dayValue)
Parameter
dayValue − An integer from 1 to 31, representing the day of the month.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCDate( 20 );
console.log( dt );
Output
Wed Aug 20 2008 23:30:00 GMT+0530 (India Standard Time)
setUTCFullYear()
Javascript date setUTCFullYear() method sets the full year for a specified date according
to universal time.
Syntax
Date.setUTCFullYear(yearValue[, monthValue[, dayValue]])
Parameter
yearValue − An integer specifying the numeric value of the year, for example,
2008.
dayValue − An integer between 1 and 31 representing the day of the month. If you
specify the dayValue parameter, you must also specify the monthValue.
204
ES6
If you do not specify the monthValue and dayValue parameters, the values returned from
the getMonth and getDate methods are used. If a parameter you specify is outside of the
expected range, setUTCFullYear attempts to update the other parameters and the date
information in the Date object accordingly. For example, if you specify 15 for monthValue,
the year is incremented by 1 (year + 1), and 3 is used for the month.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCFullYear( 2006 );
console.log( dt );
Output
Mon Aug 28 2006 23:30:00 GMT+0530 (India Standard Time)
setUTCHours()
Javascript date setUTCHours() method sets the hour for a specified date according to local
time.
Syntax
Date.setUTCHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])
Parameter
hoursValue − An integer between 0 and 23, representing the hour.
If you do not specify the minutesValue, secondsValue, and msValue parameters, the
values returned from the getUTCMinutes, getUTCSeconds, and getUTCMilliseconds
methods are used.
If a parameter you specify is outside the expected range, setUTCHours attempts to update
the date information in the Date object accordingly. For example, if you use 100 for
secondsValue, the minutes will be incremented by 1 (min + 1), and 40 will be used for
seconds.
205
ES6
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCHours( 12);
console.log( dt );
Output
Thu Aug 28 2008 17:30:00 GMT+0530 (India Standard Time)
setUTCMilliseconds()
Javascript date setUTCMilliseconds() method sets the milliseconds for a specified date
according to universal time.
Syntax
Date.setUTCMilliseconds(millisecondsValue)
Parameter
millisecondsValue − A number between 0 and 999, representing the milliseconds
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCMilliseconds( 1100);
console.log( dt );
Output
Thu Aug 28 2008 23:30:01 GMT+0530 (India Standard Time)
setUTCMinutes()
Javascript date setUTCMinutes() method sets the minutes for a specified date according
to universal time.
Syntax
206
ES6
Parameter
minutesValue − An integer between 0 and 59, representing the minutes.
If you do not specify the secondsValue and msValue parameters, the values returned from
getUTCSeconds and getUTCMilliseconds methods are used.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCMinutes(65);
console.log( dt );
Output
Fri Aug 29 2008 00:35:00 GMT+0530 (India Standard Time)
setUTCMonth()
Javascript date setUTCMonth() method sets the month for a specified date according to
universal time.
Syntax
Date.setUTCMonth ( monthvalue )
Parameter
monthValue − An integer between 0 and 11, representing the month.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
207
ES6
dt.setUTCMonth(5);
console.log( dt );
Output
Sat Jun 28 2008 23:30:00 GMT+0530 (India Standard Time)
setUTCSeconds()
Javascript date setUTCSeconds() method sets the seconds for a specified date according
to universal time.
Syntax
Date.setUTCSeconds(secondsValue[, msValue])
Parameter
secondsValue − An integer between 0 and 59, representing the seconds.
If you do not specify the msValue parameter, the value returned from the
getUTCMilliseconds methods is used.
Example
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCSeconds(65);
console.log( dt );
Output
Thu Aug 28 2008 23:31:05 GMT+0530 (India Standard Time)
208
ES6
toDateString()
Javascript date toDateString() method returns the date portion of a Date object in human
readable form.
Syntax
Date.toDateString()
Return Value
Returns the date portion of a Date object in human readable form.
Example
var dt = new Date(1993, 6, 28, 14, 39, 7);
console.log( "Formated Date : " + dt.toDateString() )
Output
Formated Date : Wed Jul 28 1993
toLocaleDateString()
Javascript date toLocaleDateString() method converts a date to a string, returning the
"date" portion using the operating system's locale's conventions.
Syntax
Date.toLocaleString()
Return Value
Returns the "date" portion using the operating system's locale's conventions.
Example
var dt = new Date(1993, 6, 28, 14, 39, 7);
console.log( "Formated Date : " + dt.toLocaleDateString())
Output
Formated Date : 7/28/1993
209
ES6
toLocaleString()
Javascript date toLocaleString() method converts a date to a string, using the operating
system's local conventions.
The toLocaleString method relies on the underlying operating system in formatting dates.
It converts the date to a string using the formatting convention of the operating system
where the script is running. For example, in the United States, the month appears before
the date (04/15/98), whereas in Germany the date appears before the month (15.04.98).
Syntax
Date.toLocaleString ()
Return Value
Returns the formatted date in a string format.
Example
var dt = new Date(1993, 6, 28, 14, 39, 7);
console.log( "Formated Date : " + dt.toLocaleString() );
Output
Formated Date : 7/28/1993, 2:39:07 PM
toLocaleTimeString()
Javascript date toLocaleTimeString() method converts a date to a string, returning the
"date" portion using the current locale's conventions.
Syntax
Date.toLocaleTimeString ()
Return Value
Returns the formatted date in a string fromat.
Example
210
ES6
Output
Formated Date : 2:39:07 PM
toString()
This method returns a string representing the specified Date object.
Syntax
Date.toString ()
Return Value
Returns a string representing the specified Date object.
Example
var dateobject = new Date(1993, 6, 28, 14, 39, 7);
stringobj = dateobject.toString();
console.log( "String Object : " + stringobj );
Output
String Object : Wed Jul 28 1993 14:39:07 GMT+0000 (UTC)
toTimeString()
This method returns the time portion of a Date object in human readable form.
Syntax
Date.toTimeString ()
Return Value
Returns the time portion of a Date object in human readable form.
211
ES6
Example
var dateobject = new Date(1993, 6, 28, 14, 39, 7);
console.log( dateobject.toTimeString() );
Output
14:39:07 GMT+0530 (India Standard Time)
toUTCString()
This method converts a date to a string, using the universal time convention.
Syntax
Date.toUTCString ()
Return Value
Returns converted date to a string, using the universal time convention.
Example
var dateobject = new Date(1993, 6, 28, 14, 39, 7);
console.log( dateobject.toUTCString() );
Output
Wed, 28 Jul 1993 09:09:07 GMT
valueof()
This method returns the primitive value of a Date object as a number data type, the
number of milliseconds since midnight 01 January, 1970 UTC.
Syntax
Date.valueOf()
Return Value
Returns the primitive value of a Date object.
Example
212
ES6
Output
743850547000
213
23. ES6 − Math ES6
The math object provides you properties and methods for mathematical constants and
functions. Unlike other global objects, Math is not a constructor. All the properties and
methods of Math are static and can be called by using Math as an object without creating
it.
Math Properties
Following is a list of all Math properties and its description.
Property Description
E Euler's constant and the base of natural logarithms, approximately 2.718
LN2 Natural logarithm of 2, approximately 0.693
LN10 Natural logarithm of 10, approximately 2.302
LOG2E Base 2 logarithm of E, approximately 1.442
LOG10E Base 10 logarithm of E, approximately 0.434
Ratio of the circumference of a circle to its diameter, approximately
PI
3.14159
Square root of 1/2; equivalently, 1 over the square root of 2,
SQRT1_2
approximately 0.707
SQRT2 Square root of 2, approximately 1.414
Math- E
This is an Euler's constant and the base of natural logarithms, approximately 2.718.
Syntax
Math.E
Example
console.log(Math.E) // the root of the natural logarithm: ~2.718
Output
2.718281828459045
Math- LN2
It returns the natural logarithm of 2 which is approximately 0.693.
Syntax
214
ES6
Math.LN2
Example
console.log(Math.LN2) // the natural logarithm of 2: ~0.693
Output
0.6931471805599453
Math- LN10
Natural logarithm of 10, approximately 2.302
Syntax
Math.LN2
Example
console.log(Math.LN10) // the natural logarithm of 10: ~2.303
Output
2.302585092994046
Math- LOG2E
Base 2 logarithm of E, approximately 1.442
Syntax
Math.LOG2E
Example
console.log(Math.LOG2E) // the base 2 logarithm of Math.E: ~1.433
Output
1.4426950408889634
215
ES6
Math - LOG10E
Base 10 logarithm of E, approximately 0.434.
Syntax
Math.LOG10E
Example
console.log(Math.LOG10E) // the base 10 logarithm of Math.E: 0.434
Output
0.4342944819032518
Math- PI
Ratio of the circumference of a circle to its diameter, approximately 3.14159
Syntax
Math.PI
Example
console.log(Math.PI)
// the ratio of a circle's circumference to its diameter: ~3.142
Output
3.141592653589793
Math- SQRT1_2
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707
Syntax
Math.SQRT1_2
Example
console.log(Math.SQRT1_2) // the square root of 1/2: ~0.707
216
ES6
Output
0.7071067811865476
Math - SQRT2
Square root of 2, approximately 1.414
Syntax
Math.SQRT2
Example
console.log(Math.SQRT2) // the square root of 2: ~1.414
Output
1.4142135623730951
Exponential Functions
The basic exponential function is Math.pow(), and there are convenience functions for
square root, cube root, and powers of e, as shown in the following table.
Function Description
Pow()
This method returns the base to the exponent power, that is, base to the power exponent.
217
ES6
Syntax
Math.pow(x, y)
Parameter
x: represents base
y: represents the exponent
Return Value
Returns the base to the exponent power.
Example
console.log("---Math.pow()---")
console.log("math.pow(2,3) : "+Math.pow(2, 3))
console.log("Math.pow(1.7, 2.3) : "+Math.pow(1.7, 2.3))
Output
---Math.pow()---
math.pow(2,3) : 8
Math.pow(1.7, 2.3) : 3.388695291147646
sqrt()
This method returns the square root of a number. If the value of a number is negative,
sqrt returns NaN.
Syntax
Math.sqrt ( x );
Parameter
x: represents a number
Return Value
Returns the square root of the number.
Example
console.log("---Math.sqrt()---")
console.log("Math.sqrt(16) : "+Math.sqrt(16))
218
ES6
console.log("Math.sqrt(15.5) : "+Math.sqrt(15.5))
Output
---Math.sqrt()---
Math.sqrt(16) : 4
Math.sqrt(15.5) : 3.9370039370059056
cbrt()
This method returns the cube root of a number.
Syntax
Math.cbrt ( x );
Parameter
x: represents a number
Return Value
Returns the cube root of the number.
Example
console.log("---Math.cbrt()---")
console.log("Math.cbrt(27) : "+Math.cbrt(27))
console.log("Math.cbrt(22) : "+Math.cbrt(22))
Output
---Math.cbrt()---
Math.cbrt(27) : 3
Math.cbrt(22) : 2.802039330655387
exp()
Equivalent to Math.pow(Math.E, x)
Syntax
219
ES6
Math.exp ( x ) ;
Parameter
x: represents a number
Return Value
Returns the exponential value of the variable x.
Example
console.log("---Math.exp()---")
console.log("Math.exp(1) : "+Math.exp(1))
console.log("Math.exp(5.5) : "+Math.exp(5.5))
Output
---Math.exp()---
Math.exp(1) : 2.718281828459045
Math.exp(5.5) : 244.69193226422036
expm1(X)
Equivalent to Math.exp(x) – 1
Syntax
Math.expm1( x ) ;
Parameter
x: represents a number
Return Value
Returns the value of Math.exp(x) – 1
Example
console.log("---Math.expm1()---")
console.log("Math.expm1(1) : "+Math.expm1(1))
console.log("Math.expm1(5.5) : "+Math.expm1(5.5))
220
ES6
Output
---Math.expm1()---
Math.expm1(1) : 1.718281828459045
Math.expm1(5.5) : 243.69193226422038
Math.hypot(x1, x2,...)
Returns the square root of the sum of the arguments
Syntax
Math.hypot( x1,x2.. ) ;
Parameter
X1 and x2..: represents numbers
Return Value
Returns the square root of the sum of all the numbers passed a argument
Example
console.log("---Math.hypot()---")
console.log("Math.hypot(3,4) : "+Math.hypot(3,4))
console.log("Math.hypot(2,3,4) : "+Math.hypot(2,3,4))
Output
---Math.hypot()---
Math.hypot(3,4) : 5
Math.hypot(2,3,4) : 5.385164807134504
Logarithmic Functions
The basic natural logarithm function is Math.log (). In JavaScript, “log” means “natural
logarithm.” ES6 introduced Math.log10 for convenience.
Function Description
221
ES6
Math.log(x)
Returns the natural logarithm of X
Syntax
Math.log(x)
Parameter
x: represents a number
Example
console.log("---Math.log()---")
console.log("Math.log(Math.E): "+Math.log(Math.E))
console.log("Math.log(17.5): "+Math.log(17.5))
Output
---Math.log()---
Math.log(Math.E): 1
Math.log(17.5): 2.8622008809294686
Math.log10(x)
Returns the base 10 logarithm of X
Syntax
Math.log10(x)
Parameter
x: represents a number
222
ES6
Example
console.log("---Math.log10()---")
console.log("Math.log10(10): "+Math.log10(10))
console.log("Math.log10(16.7): "+Math.log10(10))
Output
---Math.log10()---
Math.log10(10): 1
Math.log10(16.7): 1
Math.log2(x)
Returns the base 2 logarithm of X
Syntax
Math.log2(x)
Parameter
x: represents a number
Example
console.log("---Math.log2()---")
console.log("Math.log2(2): "+Math.log2(2))
console.log("Math.log2(5): "+Math.log2(5))
Output
---Math.log2()---
Math.log2(2): 1
Math.log2(5): 2.321928094887362
Math.log1p(x)
Returns the natural logarithm of 1+x
223
ES6
Syntax
Math.log1p(x)
Parameter
x: represents a number
Example
console.log("---Math.log1p()---")
console.log("Math.log1p(Math.E - 1): "+Math.log1p(Math.E - 1))
console.log("Math.log1p(17.5): "+Math.log1p(17.5))
---Math.log1p()---
Math.log1p(Math.E - 1): 1
Math.log1p(17.5): 2.917770732084279
Function Description
Abs()
This method returns the absolute value of a number.
Syntax
Math.abs( x ) ;
Parameter
X: represents a number
224
ES6
Return Value
Returns the absolute value of a number
Example
console.log("---Math.abs()---")
console.log("Math.abs(-5.5) : "+Math.abs(-5.5))
console.log("Math.abs(5.5) : "+Math.abs(5.5))
Output
---Math.abs()---
Math.abs(-5.5) : 5.5
Math.abs(5.5) : 5.5
sign()
Returns the sign of x
Syntax
Math.sign( x ) ;
Parameter
X: represents a number
Return Value
Returns -1 if x is negative; 1 if x is positive;0 if x is 0.
Example
console.log("---Math.sign()---")
console.log("Math.sign(-10.5) : "+Math.sign(-10.5))
console.log("Math.sign(6.77) : "+Math.sign(6.77))
Output
---Math.sign()---
Math.sign(-10.5) : -1
Math.sign(6.77) : 1
225
ES6
round()
It rounds off the number to the nearest integer.
Syntax
Math.round( x ) ;
Parameter
X: represents a number
Example
console.log("---Math.round()---")
console.log("Math.round(7.2) : "+Math.round(7.2))
console.log("Math.round(-7.7) : "+Math.round(-7.7))
Output
---Math.round()---
Math.round(7.2) : 7
Math.round(-7.7) : -8
trunc()
It returns the integral part of x (all fractional digits are removed).
Syntax
Math.trunc( x ) ;
Parameter
X: represents a number
Example
console.log("---Math.trunc()---")
console.log("Math.trunc(7.7) : "+Math.trunc(7.7))
console.log("Math.trunc(-5.8) : "+Math.trunc(-5.8))
226
ES6
Output
---Math.trunc()---
Math.trunc(7.7) : 7
Math.trunc(-5.8) : -5
floor()
The floor of x: the largest integer less than or equal to x.
Syntax
Math.floor( x ) ;
Parameter
X: represents a number
Example
console.log("---Math.floor()---")
console.log("Math.floor(2.8) : "+Math.floor(2.8))
console.log("Math.floor(-3.2) : "+Math.floor(-3.2))
Output
---Math.floor()---
Math.floor(2.8) : 2
Math.floor(-3.2) : -4
ceil()
This method returns the smallest integer greater than or equal to a number.
Syntax
Math.ceil ( x ) ;
Parameter
X: represents a number
227
ES6
Example
console.log("---Math.ceil()---")
console.log("Math.ceil(2.2) : "+Math.ceil(2.2))
console.log("Math.ceil(-3.8) : "+Math.ceil(-3.8))
Output
---Math.ceil()---
Math.ceil(2.2) : 3
Math.ceil(-3.8) : -3
min()
This method returns the smallest of zero or more numbers. If no arguments are given, the
results is +Infinity.
Syntax
Math.min( x1,x2,… ) ;
Parameter
X1,x2,x3..: represents a series of numbers
Example
console.log("---Math.min()---")
console.log("Math.min(1, 2) : "+Math.min(1, 2))
console.log("Math.min(3, 0.5, 0.66) : "+Math.min(3, 0.5, 0.66))
console.log("Math.min(3, 0.5, -0.66) : "+Math.min(3, 0.5, -0.66))
Output
---Math.min()---
Math.min(1, 2) : 1
Math.min(3, 0.5, 0.66) : 0.5
Math.min(3, 0.5, -0.66) : -0.66
228
ES6
max()
This method returns the largest of zero or more numbers. If no arguments are given, the
results is –Infinity.
Syntax
Math.max(x1,x2,x3..)
Parameter
x1, x2, x3.. : represents a series of numbers
Example
console.log("---Math.max()---")
console.log("Math.max(3, 0.5, 0.66) : "+Math.max(3, 0.5, 0.66))
console.log("Math.max(-3, 0.5, -0.66) : "+Math.max(-3, 0.5, -0.66))
---Math.max()---
Math.max(3, 0.5, 0.66) : 3
Math.max(-3, 0.5, -0.66) : 0.5
Trigonometric Functions
All trigonometric functions in the Math library operate on radians, not degrees.
Function Description
229
ES6
Math.sin(x)
This function returns the sine of x radians.
Syntax
Math.sin(x)
Parameter
X : represents a number
Example
console.log("---Math.sin()---")
console.log("Math.sin(Math.PI/2): "+Math.sin(Math.PI/2))
console.log("Math.sin(Math.PI/4): "+Math.sin(Math.PI/4))
Output
---Math.sin()---
Math.sin(Math.PI/2): 1
Math.sin(Math.PI/4): 0.7071067811865475
Math.cos(x)
It returns the cosine of x radians.
Syntax
Math.cos(x)
Parameter
X : represents a number
230
ES6
Example
console.log("---Math.cos()---")
console.log("Math.cos(Math.PI): "+Math.cos(Math.PI))
console.log("Math.cos(Math.PI/4): "+Math.PI/4)
Output
---Math.cos()---
Math.cos(Math.PI): -1
Math.cos(Math.PI/4): 0.7853981633974483
Math.tan(x)
This function returns the tangent of x.
Syntax
Math.tan(x)
Parameter
X : represents a number
Example
console.log("---Math.tan()---")
console.log("Math.tan(Math.PI/4): "+Math.tan(Math.PI/4))
console.log("Math.tan(0): "+Math.tan(0))
Output
---Math.tan()---
Math.tan(Math.PI/4): 0.9999999999999999
Math.tan(0): 0
Math.asin(x)
This function returns the inverse sine of x.
231
ES6
Syntax
Math.asin(x)
Parameter
X : represents a number
Example
console.log("---Math.asin()---")
console.log("Math.asin(0): "+Math.asin(0))
console.log("Math.asin(Math.SQRT1_2): "+Math.asin(Math.SQRT1_2))
Output
---Math.asin()---
Math.asin(0): 0
Math.asin(Math.SQRT1_2): 0.7853981633974484
Math.acos(x)
This function returns the inverse cosine of x.
Syntax
Math.acos(x)
Parameter
X : represents a number
Example
console.log("---Math.acos()---")
console.log("Math.acos(0): "+Math.acos(0))
console.log("Math.acos(Math.SQRT1_2): "+Math.acos(Math.SQRT1_2))
Output
---Math.acos()---
Math.acos(0): 1.5707963267948966
Math.acos(Math.SQRT1_2): 0.7853981633974483
232
ES6
Math.atan(x)
It returns the inverse tangent of x.
Syntax
Math.atan(x)
Parameter
X : represents a number
Example
console.log("---Math.atan()---")
console.log("Math.atan(0): "+Math.atan(0))
console.log("Math.atan(Math.SQRT1_2): "+Math.atan(Math.SQRT1_2))
Output
---Math.atan()---
Math.atan(0): 0
Math.atan(Math.SQRT1_2): 0.6154797086703874
Math.atan2()
This method returns the arctangent of the quotient of its arguments. The atan2 method
returns a numeric value between -pi and pi representing the angle theta of an (x, y) point.
Syntax
Math.atan2(x,y)
Parameter
x and y: represent numbers
Example
console.log("---Math.atan2()---")
console.log("Math.atan2(0): "+Math.atan2(0,1))
console.log("Math.atan2(Math.SQRT1_2): "+Math.atan2(1,1))
Output
233
ES6
---Math.atan2()---
Math.atan2(0): 0
Math.atan2(Math.SQRT1_2): 0.7853981633974483
Math.random()
The Math.random() function returns a pseudorandom number between 0 (inclusive) and
1 (exclusive).
Output
First Test Value : 0.5782922627404332
Second Test Value : 0.5624510529451072
Third Test Value : 0.9336334094405174
Fourth Test Value : 0.4002739654388279
234
24. ES6 − RegExp ES6
The JavaScript RegExp class represents regular expressions, and both String and RegExp
define methods that use regular expressions to perform powerful pattern-matching and
search-and-replace functions on the text.
Attribute Description
G Global match
I Ignore case
Sticky; matches only from the index indicated by the lastIndex property
Y of this regular expression in the target string (and does not attempt to
match from any later indexes)
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions.
They are used to find a range of characters.
235
ES6
Expression Description
The ranges shown above are general; you could also use the range [0-3] to match any
decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase
character ranging from b through v.
Quantifiers
The frequency or position of the bracketed character sequences and the single characters
can be denoted by a special character. Each special character has a specific connotation.
The +, *, ?, and $ flags all follow a character sequence.
Expression Description
236
ES6
It matches any string not containing any of the characters ranging from
[^a-zA-Z]
a through z and A through Z
<b>(.*)</b
It matches any string enclosed within <b> and </b>
>
Literal Characters
Character Description
Alphanumeric Itself
\t Tab (\u0009)
\n Newline (\u000A)
237
ES6
The control character ^X; for example, \cJ is equivalent to the newline
\cX
character \n
Meta-characters
A meta-character is simply an alphabetical character preceded by a backslash that acts
to give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d' meta-character:
/([\d]+)000/. Here, \d will search for any string of the numerical character.
The following table lists a set of meta-characters which can be used in PERL Style Regular
Expressions.
Character Description
. A single character
\S Non-whitespace character
\d A digit (0-9)
\D A non-digit
\W A non-word character
238
ES6
RegExp Properties
Properties Description
RegExp Constructor
It returns a reference to the array function that created the instance's prototype.
Syntax
RegExp.constructor
Return Value
Returns the function that created this object's instance.
Example
var re = new RegExp( "string" );
console.log("re.constructor is:" + re.constructor);
Output
re.constructor is:function RegExp() { [native code] }
239
ES6
global
global is a read-only boolean property of RegExp objects. It specifies whether a particular
regular expression performs global matching, i.e., whether it was created with the "g"
attribute.
Syntax
RegExpObject.global
Return Value
Returns "TRUE" if the "g" modifier is set, "FALSE" otherwise.
Example
var re = new RegExp( "string" );
if ( re.global )
{
console.log("Test1 - Global property is set");
}
else
{
console.log("Test1 - Global property is not set");
}
re = new RegExp( "string", "g" );
if ( re.global ){
console.log("Test2 - Global property is set");
}
else
{
console.log("Test2 - Global property is not set");
}
Output
Test1 - Global property is not set
Test2 - Global property is set
240
ES6
ignoreCase
ignoreCase is a read-only boolean property of RegExp objects. It specifies whether a
particular regular expression performs case-insensitive matching, i.e., whether it was
created with the "i" attribute.
Syntax
RegExpObject.ignoreCase
Return Value
Returns "TRUE" if the "i" modifier is set, "FALSE" otherwise.
Example
var re = new RegExp( "string" );
if ( re.ignoreCase ){
console.log("Test1-ignoreCase property is set");
}
else
{
console.log("Test1-ignoreCase property is not set");
}
re = new RegExp( "string", "i" );
if ( re.ignoreCase ){
console.log("Test2-ignoreCase property is set");
}
else
{
console.log("Test2-ignoreCase property is not set");
}
Output
Test1-ignoreCase property is not set
Test2-ignoreCase property is set
241
ES6
lastIndex
lastIndex a read/write property of RegExp objects. For regular expressions with the "g"
attribute set, it contains an integer that specifies the character position immediately
following the last match found by the RegExp.exec() and RegExp.test() methods. These
methods use this property as the starting point for the next search they conduct.
This property allows you to call those methods repeatedly, to loop through all matches in
a string and works only if the "g" modifier is set.
This property is read/write, so you can set it at any time to specify where in the target
string, the next search should begin. exec() and test() automatically reset the lastIndex
to 0 when they fail to find a match (or another match).
Syntax
RegExpObject.lastIndex
Return Value
Returns an integer that specifies the character position immediately following the last
match.
Example
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
re.test(str);
console.log("Test 1 - Current Index: " + re.lastIndex);
re.test(str);
console.log("Test 2 - Current Index: " + re.lastIndex)
Output
Test 1 - Current Index: 10
Test 2 - Current Index: 35
multiline
multiline is a read-only boolean property of RegExp objects. It specifies whether a
particular regular expression performs multiline matching, i.e., whether it was created
with the "m" attribute.
Syntax
RegExpObject.multiline
242
ES6
Return Value
Returns "TRUE" if the "m" modifier is set, "FALSE" otherwise.
Example
var re = new RegExp( "string" );
if ( re.multiline ){
console.log("Test1-multiline property is set");
}
else
{
console.log("Test1-multiline property is not set");
}
re = new RegExp( "string", "m" );
if ( re.multiline ){
console.log("Test2-multiline property is set");
}
else
{
console.log("Test2-multiline property is not set");
}
Output
Test1-multiline property is not set
Test2-multiline property is set
source
source is a read-only string property of RegExp objects. It contains the text of the RegExp
pattern. This text does not include the delimiting slashes used in regular-expression
literals, and it does not include the "g", "i", and "m" attributes.
Syntax
RegExpObject.source
Return Value
Returns the text used for pattern matching.
243
ES6
Example
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
re.test(str);
console.log("The regular expression is : " + re.source);
Output
The regular expression is : script
RegExp Methods
Methods Description
exec()
The exec method searches string for text that matches regexp. If it finds a match, it
returns an array of results; otherwise, it returns null.
Syntax
RegExpObject.exec( string );
244
ES6
Parameter Details
string − The string to be searched
Return Value
It returns the matched text if a match is found, and NULL if not.
Example
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.exec(str);
console.log("Test 1 - returned value : " + result);
re = new RegExp( "pushing", "g" );
var result = re.exec(str);
console.log("Test 2 - returned value : " + result)
Output
Test 1 - returned value : script
Test 2 - returned value : null
test()
The test method searches string for text that matches regexp. If it finds a match, it returns
true; otherwise, it returns false.
Syntax
RegExpObject.test( string );
Parameter Details
string − The string to be searched
Return Value
Returns the matched text if a match is found, and NULL if not.
Example
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.test(str);
245
ES6
Output
Test 1 - returned value : true
Test 2 - returned value : false
match()
This method retrieves the matches.
Syntax
str.match(regexp)
Parameter Details
Regexp: A regular expression object.
Return Value
Returns an array of matches and null if no matches are found.
Example
var str = 'Welcome to ES6.We are learning ES6';
var re = new RegExp("We");
var found = str.match(re);
console.log(found);
Output
We
replace()
This method returns a new string after replacing the matched pattern.
Syntax
str.replace(regexp|substr, newSubStr|function)
246
ES6
Parameter Details
Regexp: A regular expression object.
Substr: String to be replaced
newSubStr: The replacement string
function: the function to create a new string
Return Value
A new string after replacing all matches.
Example
var str = 'Good Morning';
var newstr = str.replace('Morning', 'Night');
console.log(newstr);
Output
Good Night
search()
This method returns the index where the match was found in the string. If no match is
found, it returns -1.
Syntax
str.replace(regexp|substr, newSubStr|function)
Parameter Details
Regexp: A regular expression object.
Substr: String to be replaced
newSubStr: The replacement string
function: the function to create a new string
Return Value
Returns the index at which the match was found in the string
Example
var str = 'Welcome to ES6.We are learning ES6';
var re = new RegExp(/We/);
247
ES6
Output
0
split()
This method splits a string object on the basis of the separator specified and returns an
array of strings.
Syntax
str.split([separator[, limit]])
Parameter Details
separator : Optional. Specifies the separator character for the string
limit: Optional. Specifies a limit on the number of splits to be found
Return Value
Returns the index at which the match was found in the string
Example
var names = 'Monday;Tuesday;Wednesday';
console.log(names);
var re = /\s*;\s*/;
var nameList = names.split(re);
console.log(nameList););
Output
Monday;Tuesday;Wednesday
Monday,Tuesday,Wednesday
248
ES6
toString()
The toStringmethod returns a string representation of a regular expression in the form of
a regular-expression literal.
Syntax
RegExpObject.toString();
Return Value
Returns the string representation of a regular expression.
Example
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.toString(str);
console.log("Test 1 - returned value : " + result);
re = new RegExp( "/", "g" );
var result = re.toString(str);
console.log("Test 2 - returned value : " + result)
Output
Test 1 - returned value : /script/g
Test 2 - returned value : /\//g
249
25. ES6 − HTML DOM ES6
Every web page resides inside a browser window, which can be considered as an object.
A document object represents the HTML document that is displayed in that window. The
document object has various properties that refer to other objects which allow access to
and modification of the document content.
The way a document content is accessed and modified is called the Document Object
Model, or DOM. The objects are organized in a hierarchy. This hierarchical structure
applies to the organization of objects in a web document.
There are several DOMs in existence. The following sections explain each of these DOMs
in detail and describe how you can use them to access and modify the document content.
The Legacy DOM: This is the model which was introduced in early versions of
JavaScript language. It is well supported by all browsers, but allows access only to
certain key portions of documents, such as forms, form elements, and images.
The W3C DOM: This document object model allows access and modification of all
document content and is standardized by the World Wide Web Consortium (W3C).
This model is supported by almost all the modern browsers.
The IE4 DOM: This document object model was introduced in Version 4 of
Microsoft's Internet Explorer browser. IE 5 and later versions include support for
most basic W3C DOM features.
250
ES6
This model provides several read-only properties, such as title, URL, and lastModified
provide information about the document as a whole. Apart from that, there are various
methods provided by this model which can be used to set and get the document property
values.
alinkColor
1 Deprecated - A string that specifies the color of activated links.
Example: document.alinkColor
anchors[ ]
An array of anchor objects, one for each anchor that appears in the
2 document.
Example: document.anchors[0], document.anchors[1] and so on
applets[ ]
An array of applet objects, one for each applet that appears in the
3
document.
Example: document.applets[0], document.applets[1] and so on
bgColor
Deprecated - A string that specifies the background color of the
4
document.
Example: document.bgColor
Cookie
A string valued property with special behavior that allows the cookies
5
associated with this document to be queried and set.
Example: document.cookie
251
ES6
Domain
A string that specifies the Internet domain the document is from. Used
6
for security purposes.
Example: document.domain
embeds[ ]
An array of objects that represent data embedded in the document with
7 the <embed> tag. A synonym for plugins []. Some plugins and ActiveX
controls can be controlled with JavaScript code.
Example: document.embeds[0], document.embeds[1] and so on
fgColor
8 A string that specifies the default text color for the document.
Example: document.fgColor
forms[ ]
An array of form objects, one for each HTML form that appears in the
9
document.
Example: document.forms[0], document.forms[1] and so on
images[ ]
An array of image objects, one for each image that is embedded in the
10
document with the HTML <img> tag.
Example: document.images[0], document.images[1] and so on
lastModified
A read-only string that specifies the date of the most recent change to
11
the document.
Example: document.lastModified
linkColor
12 Deprecated - A string that specifies the color of unvisited links.
Example: document.linkColor
links[ ]
13 It is a document link array.
Example: document.links[0], document.links[1] and so on
Location
14 The URL of the document. Deprecated in favor of the URL property.
Example: document.location
plugins[ ]
15
A synonym for the embeds[ ]
Example: document.plugins[0], document.plugins[1] and so on
252
ES6
Referrer
A read-only string that contains the URL of the document, if any, from
16
which the current document was linked.
Example: document.referrer
Title
17 The text contents of the <title> tag.
Example: document.title
URL
18 A read-only string that specifies the URL of the document.
Example: document.URL
vlinkColor
19 Deprecated - A string that specifies the color of the visited links.
Example: document.vlinkColor
clear( )
Deprecated - Erases the contents of the document and returns nothing.
1
Example: document.clear( )
close( )
2 Closes a document stream opened with the open( ) method and returns
nothing.
open( )
Deletes the existing document content and opens a stream to which the
3 new document contents may be written. Returns nothing.
Example: document.open( )
253
ES6
We can locate any HTML element within any HTML document using HTML DOM. For
instance, if a web document contains a form element, then using JavaScript, we can refer
to it as document.forms[0]. If your Web document includes two form elements, the first
form is referred to as document.forms[0] and the second as document.forms[1].
Using the hierarchy and properties given above, we can access the first form element
using document.forms[0].elements[0] and so on.
Example
Following is an example to access document properties using Legacy DOM method.
<html>
<head>
<title> Document Title </title>
<script type="text/javascript">
<!--
function myFunc()
{
var ret = document.title;
alert("Document Title : " + ret );
var ret = document.URL;
alert("Document URL : " + ret );
var ret = document.forms[0];
alert("Document First Form : " + ret );
var ret = document.forms[0].elements[1];
alert("Second element : " + ret );
}
//-->
</script>
</head>
<body>
<h1 id="title">This is main title</h1>
<p>Click the following to see the result:</p>
254
ES6
<form name="FirstForm">
<input type="button" value="Click Me" onclick="myFunc();" />
<input type="button" value="Cancel">
</form>
<form name="SecondForm">
<input type="button" value="Don't ClickMe"/>
</form>
</body>
</html>
Output
The following output is displayed on successful execution of the above code.
Note: This example returns the objects for forms and elements. We would have to access
their values by using those object properties which are not discussed in this tutorial.
255
26. ES6 — Iterator ES6
Introduction to Iterator
Iterator is an object which allows us to access a collection of objects one at a time.
String
Array
Map
Set
Example
The following example declares an array, marks, and iterates through it by using
a for..of loop.
<script>
let marks = [10,20,30]
</script>
10
20
30
256
ES6
Example
The following example declares an array, marks and retrieves an iterator object.
The [Symbol.iterator]() can be used to retrieve an iterator object. The next() method
of the iterator returns an object with 'value' and 'done' properties . 'done' is Boolean and
returns true after reading all items in the collection.
<script>
let marks = [10,20,30]
let iter = marks[Symbol.iterator]();
console.log(iter.next())
console.log(iter.next())
console.log(iter.next())
console.log(iter.next())
</script>
Custom Iterable
Certain types in JavaScript are iterable (E.g. Array, Map etc.) while others are not (E.g.
Class). JavaScript types which are not iterable by default can be iterated by using the
iterable protocol.
The following example defines a class named CustomerList which stores multiple
customer objects as an array. Each customer object has firstName and lastName
properties.
To make this class iterable, the class must implement [Symbol.iterator]() function. This
function returns an iterator object. The iterator object has a function next which returns
an object {value:'customer',done:true/false}.
<script>
257
ES6
let c1={
firstName:'Sachin',
lastName:'Tendulkar'
}
let c2={
firstName:'Rahul',
lastName:'Dravid'
}
258
ES6
let customers=[c1,c2]
259
ES6
Generator
Prior to ES6, functions in JavaScript followed a run-to completion model. ES6 introduces
functions known as Generator which can stop midway and then continue from where it
stopped.
A generator prefixes the function name with an asterisk * character and contains one or
more yield statements. The yield keyword returns an iterator object.
Syntax
function * generator_name()
{
yield value1
...
yield valueN
}
Example
The example defines a generator function getMarks with three yield statements. Unlike
normal functions, the generator function getMarks(),when invoked, doesn’t execute
the function but returns an iterator object that helps you to execute code inside the
generator function.
On the first call to markIter.next() operations in the beginning would run and the yield
statement pauses the execution of the generator. Subsequent calls to
the markIter.next() will resume the generator function until the next yield expression.
<script>
//define generator function
function * getMarks(){
console.log("Step 1")
yield 10
console.log("Step 2")
yield 20
console.log("Step 3")
yield 30
console.log("End of function")
}
260
ES6
Step 1
{value: 10, done: false}
Step 2
{value: 20, done: false}
Step 3
{value: 30, done: false}
End of function
{value: undefined, done: true}
Example
The following example creates an infinite sequence of even numbers through
We can iterate through all even numbers by using next() or using for of loop as shown
below:
<script>
function * evenNumberGenerator(){
let num = 0;
while(true){
num+=2
yield num
261
ES6
console.log(iter.next())
console.log(iter.next())
</script>
2
4
6
8
10
262
27. ES6 − Collections ES6
Maps
The Map object is a simple key/value pair. Keys and values in a map may be primitive or
objects.
new Map([iterable])
The parameter iterable represents any iterable object whose elements comprise of a
key/value pair. Maps are ordered, i.e. they traverse the elements in the order of their
insertion.
Map Properties
Property Description
Syntax
Map.size
Example
var myMap = new Map();
myMap.set("J", "john");
myMap.set("M", "mary");
myMap.set("T", "tom");
console.log(myMap.size);
Output
3
263
ES6
The has() function returns a boolean value indicating whether the specified key is found
in the Map object. This function takes a key as parameter.
The above example creates a map object. The map has only one element. The element
key is denoted by name. The key is mapped to a value Tutorial point.
Note: Maps distinguish between similar values but bear different data types. In other
words, an integer key 1 is considered different from a string key “1”. Consider the
following example to better understand this concept.
Output
false
true
Output
True
264
ES6
The above example, defines a map object. The example chains the set() function to define
the key/value pair.
The get() function is used to retrieve the value corresponding to the specified key.
The Map constructor can also be passed an array. Moreover, map also supports the use of
spread operator to represent an array.
Example
var roles = new Map([
['r1', 'User'],
['r2', 'Guest'],
['r3', 'Admin'],
]);
console.log(roles.get('r2'))
Guest
Note: The get() function returns undefined if the key specified doesn’t exist in the map.
The set() replaces the value for the key, if it already exists in the map. Consider the
following example.
265
ES6
Map Methods
Method Description
clear()
Removes all key/value pairs from the Map object.
Syntax
myMap.clear();
Parameters: No parameters
266
ES6
Example
var myMap = new Map();
myMap.set("bar", "baz");
console.log(myMap.size);
myMap.clear();
console.log(myMap.size)
Output
1
0
delete(key)
Removes any value associated to the key and returns the value that
Map.prototype.has(key) would have previously returned. Map.prototype.has(key) will
return false afterwards.
Syntax
myMap.delete(key);
Parameters
Key : key of the element to be removed from the Map
Return Value
Returns true if the element exited and was removed; else it returns false.
Example
var myMap = new Map();
myMap.set("id", "admin");
myMap.set("pass", "admin@123");
console.log(myMap.has("id"));
myMap.delete("id");
console.log(myMap.has("id"));
267
ES6
Output
true
false
entries()
Returns a new Iterator object that contains an array of [key, value] for each element in
the Map object in insertion order.
Syntax
myMap.entries()
Return Value
Returns a new iterator object.
Example
var myMap = new Map();
myMap.set("id", "admin");
myMap.set("pass", "admin@123");
var itr = myMap.entries();
console.log(itr.next().value);
console.log(itr.next().value);
Output
id,admin
pass,admin@123
forEach
This function executes the specified function once per each Map entry.
Syntax
myMap.forEach(callback[, thisArg])
Parameters
callback: Function to execute for each element.
thisArg: Value to use as this when executing callback.
268
ES6
Return Value
Undefined.
Example
function userdetails(key,value) {
console.log("m[" + key + "] = " + value);
}
Output
m[admin] = id
m[admin@123] = pass
keys()
This function returns a new iterator object referring to the keys in the Map.
Syntax
myMap.keys()
Return Value
Returns an Iterator object
Example
var myMap = new Map();
myMap.set("id", "admin");
myMap.set("pass", "admin@123");
var itr=myMap.keys();
console.log(itr.next().value);
console.log(itr.next().value);
269
ES6
Output
id
pass
values()
This function returns a new iterator object referring to the values in the Map.
Syntax
myMap.keys()
Return Value
Returns an Iterator object.
Example
var myMap = new Map();
myMap.set("id", "admin");
myMap.set("pass", "admin@123");
var itr=myMap.values();
console.log(itr.next().value);
console.log(itr.next().value);
Output
Admin
admin@123
'use strict'
var roles = new Map([
['r1', 'User'],
['r2', 'Guest'],
['r3', 'Admin'],
]);
270
ES6
for(let r of roles.entries())
console.log(`${r[0]}: ${r[1]}`);
r1: User
r2: Guest
r3: Admin
Weak Maps
A weak map is identical to a map with the following exceptions:
WeakMap {}
true
Sets
A set is an ES6 data structure. It is similar to an array with an exception that it cannot
contain duplicates. In other words, it lets you store unique values. Sets support both
primitive values and object references.
Just like maps, sets are also ordered, i.e. elements are iterated in their insertion order. A
set can be initialized using the following syntax.
new Set([iterable]);
271
ES6
Set Properties
Property Description
size()
Returns the number of values in the Set object
Syntax
Myset.size
Example
var mySet = new Set('tom','jim','jack');
var tot=mySet.size;
console.log(tot);
Output
3
Set Methods
Method Description
272
ES6
add()
This method appends a new element with the given value to the Set object.
Syntax
mySet.add(value);
Parameters
Value: item to add to the list.
Return Value
Set Object.
Example
var set = new Set();
set.add(10);
set.add(10); // duplicate not added
set.add(10); // duplicate not added
set.add(20);
set.add(30);
console.log(set.size);
273
ES6
clear()
This function clears all objects from the Set.
Syntax
mySet.clear();
Return Value
Undefined
Example
var mySet = new Set('tom','jim','jack');
mySet.clear()
var tot=mySet.size;
console.log(tot);
delete()
This function removes the specified value from the Set.
Syntax
myMap.delete(key);
Parameters
Key : key of the element to be removed from the Map
Return Value
Returns true if the element exited and was removed; else it returns false.
Example
var set = new Set();
set.add(10);
set.add(20);
set.add(30);
274
ES6
Output
Size of Set before delete() :3
Set has 10 before delete() :true
Size of Set after delete() :2
Set has 10 after delete() :false
entries()
Returns a new Iterator object that contains an array of [value,value] for each element in
the Set.
Syntax
mySet.entries()
Return Value
Returns a new iterator object.
Example
var mySet = new Set();
mySet.add("Jim");
mySet.add("Jack");
mySet.add("Jane");
var itr=mySet.entries()
console.log(itr.next().value);
console.log(itr.next().value);
console.log(itr.next().value);
275
ES6
Output
Jim,Jim
Jack,Jack
Jane,Jane
forEach
This function executes the specified function once per each Map entry.
Syntax
myMap.forEach(callback[, thisArg])
Parameters
callback: Function to execute for each element.
thisArg: Value to use as this when executing callback.
Return Value
Undefined
Example
function userdetails(values) {
console.log(values);
}
Output
John
Jane
has()
Returns a boolean indicating whether an element with the specified value exists in a Set
object or not.
276
ES6
Syntax
mySet.has(value);
Parameters
Value: The value for which existence check should be done.
Return Value
Returns true if an element with the specified value exists in the Set object; otherwise
false.
Example
var mySet = new Set();
mySet.add("Jim");
console.log(mySet.has("Jim"));
console.log(mySet.has("Tom"));
Output
true
false
Syntax
mySet.values();
mySet.keys();
Return Value
A new Iterator object containing the values for each element in the given Set.
Example
var mySet = new Set();
mySet.add("Jim");
277
ES6
mySet.add("Jack");
mySet.add("Jane");
console.log("Printing keys()------------------");
var keyitr=mySet.keys();
console.log(keyitr.next().value);
console.log(keyitr.next().value);
console.log(keyitr.next().value);
console.log("Printing values()------------------");
var valitr=mySet.values();
console.log(valitr.next().value);
console.log(valitr.next().value);
console.log(valitr.next().value);
Output
Printing keys()------------------
Jim
Jack
Jane
Printing values()------------------
Jim
Jack
Jane
278
ES6
x
y
z
Weak Set
Weak sets can only contain objects, and the objects they contain may be garbage
collected. Like weak maps, weak sets cannot be iterated.
true
false
Iterator
Iterator is an object which allows to access a collection of objects one at a time. Both set
and map have methods which returns an iterator.
Iterators are objects with next() method. When next() method is invoked, it returns an
object with 'value' and 'done' properties . 'done' is boolean, this will return true after
reading all items in the collection.
279
ES6
Since, the set does not store key/value, the value array contains similar key and value.
done will be false as there are more elements to be read.
281
28. ES6 − Classes ES6
Let us translate these Object-Oriented concepts to the ones in the real world. For example:
A car is an object that has data (make, model, number of doors, Vehicle Number, etc.)
and functionality (accelerate, shift, open doors, turn on headlights, etc.)
Prior to ES6, creating a class was a fussy affair. Classes can be created using the class
keyword in ES6.
Classes can be included in the code either by declaring them or by using class expressions.
282
ES6
The class keyword is followed by the class name. The rules for identifiers (already
discussed) must be considered while naming a class.
Constructors: Responsible for allocating memory for the objects of the class.
Functions: Functions represent actions an object can take. They are also at times
referred to as methods.
These components put together are termed as the data members of the class.
Note: A class body can only contain methods, but not data properties.
283
ES6
The above code snippet represents an unnamed class expression. A named class
expression can be written as:
Creating Objects
To create an instance of the class, use the new keyword followed by the class name.
Following is the syntax for the same.
Where,
The right hand side of the expression invokes the constructor. The constructor
should be passed values if it is parameterized.
Accessing Functions
A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot
notation (called as the period) to access the data members of a class.
//accessing a function
obj.function_name()
284
ES6
}
test()
{
console.log("The height of the polygon: ", this.h)
console.log("The width of the polygon: ",this. w)
}
}
//creating an instance
The Example given above declares a class ‘Polygon’. The class’s constructor takes two
arguments - height and width respectively. The ‘this’ keyword refers to the current
instance of the class. In other words, the constructor above initializes two variables h and
w with the parameter values passed to the constructor. The test () function in the class,
prints the values of the height and width.
To make the script functional, an object of the class Polygon is created. The object is
referred to by the polyObj variable. The function is then called via this object.
Setters
A setter function is invoked when there is an attempt to set the value of a property.
The set keyword is used to define a setter function. The syntax for defining a setter
function is given below:
{set prop(val) { . . . }}
{set [expression](val) { . . . }}
prop is the name of the property to bind to the given function. val is an alias for the
variable that holds the value attempted to be assigned to property. expression with ES6,
can be used as a property name to bind to the given function.
Example
<script>
285
ES6
class Student {
constructor(rno,fname,lname){
this.rno = rno
this.fname = fname
this.lname = lname
console.log('inside constructor')
}
set rollno(newRollno){
console.log("inside setter")
this.rno = newRollno
}
}
</script>
The above example defines a class Student with three properties namely rno, fname
and lname. A setter function rollno() is used to set the value for the rno property.
inside constructor
Student {rno: 101, fname: "Sachin", lname: "Tendulkar"}
inside setter
Student {rno: 201, fname: "Sachin", lname: "Tendulkar"}
Example
The following example shows how to use an expression as a property name with a setter
function.
<script>
let expr = 'name';
286
ES6
let obj = {
fname: 'Sachin',
set [expr](v) { this.fname = v; }
};
console.log(obj.fname);
obj.name = 'John';
console.log(obj.fname);
</script>
Sachin
John
Getters
A getter function is invoked when there is an attempt to fetch the value of a property.
The get keyword is used to define a getter function. The syntax for defining a getter
function is given below:
Example
<script>
class Student {
constructor(rno,fname,lname){
this.rno = rno
this.fname = fname
this.lname = lname
console.log('inside constructor')
}
get fullName(){
287
ES6
console.log('inside getter')
return this.fname + " - "+this.lname
}
}
</script>
The above example defines a class Student with three properties namely rno, fname and
lname. The getter function fullName() concatenates the fname and lname and returns
a new string.
inside constructor
Student {rno: 101, fname: "Sachin", lname: "Tendulkar"}
inside getter
Sachin - Tendulkar
Example
The following example shows how to use an expression as a property name with a getter
function:
<script>
let expr = 'name';
let obj = {
get [expr]() { return 'Sachin'; }
};
console.log(obj.name);
</script>
Sachin
288
ES6
Example
'use strict'
class StaticMem
{
static disp()
{
console.log("Static Function called")
}
}
StaticMem.disp() //invoke the static method
Note: It is not mandatory to include a constructor definition. Every class by default has a
constructor by default.
Example
'use strict'
class Person{ }
var obj=new Person()
var isPerson=obj instanceof Person;
console.log(" obj is an instance of Person " + isPerson);
Class Inheritance
ES6 supports the concept of Inheritance. Inheritance is the ability of a program to create
new entities from an existing entity - here a class. The class that is extended to create
289
ES6
newer classes is called the parent class/super class. The newly created classes are
called the child/sub classes.
A class inherits from another class using the ‘extends’ keyword. Child classes inherit all
properties and methods except constructors from the parent class.
The above example declares a class Shape. The class is extended by the Circle class. Since,
there is an inheritance relationship between the classes, the child class i.e., the class Car
gets an implicit access to its parent class attribute i.e., area.
Single: Every class can at the most extend from one parent class
Multiple: A class can inherit from multiple classes. ES6 doesn’t support multiple
inheritance.
290
ES6
'use strict'
class Root
{
test()
{
console.log("call from parent class")
}
}
class Child extends Root
{}
class Leaf extends Child
//indirectly inherits from Root by virtue of inheritance
{}
var obj= new Leaf();
obj.test()
The class Leaf derives the attributes from the Root and the Child classes by virtue of multi-
level inheritance.
'use strict'
class PrinterClass
{
doPrint()
{
console.log("doPrint() from Parent called…
}
291
ES6
{
console.log("doPrint() is printing a string…") }
}
var obj= new StringPrinter()
obj.doPrint()
In the above Example, the child class has changed the superclass function’s
implementation.
'use strict'
class PrinterClass
{
doPrint()
{console.log("doPrint() from Parent called…") }
}
The doPrint() redefinition in the class StringWriter, issues a call to its parent class
version. In other words, the super keyword is used to invoke the doPrint() function
definition in the parent class - PrinterClass.
293
29. ES6 — Maps and Sets ES6
ES6 introduces two new data structures: maps and sets. Let us learn about them in detail.
Maps
A map is an ordered collection of key-value pairs. Maps are similar to objects. However,
there are some differences between maps and objects. These are listed below:
S. No Object Map
Syntax
The syntax for Map is given below:
Example
The following example creates a map using an iterable constructor:
<script>
let andy ={ename:"Andrel"},
varun = {ename:"Varun"},
prijin={ename:"Prijin"}
let empJobs = new Map([
[andy,'Software Architect'],
[varun,'Developer']]
);
console.log(empJobs)
</script>
294
ES6
Syntax
The syntax for checking the size of the map is given below:
map_name.size
Example
<script>
let daysMap = new Map();
daysMap.set('1', 'Monday');
daysMap.set('2', 'Tuesday');
daysMap.set('3', 'Wednesday');
console.log(daysMap.size);
</script>
Following are some common methods that can be used to manipulate maps:
S. No Object Map
295
ES6
S. No Object Map
set()
This function adds key and value to map.
Syntax
The syntax for set() is given below where, key is the key of the element to add to the
Map object and value is the value of the element to add to the Map object.
map_name.set(key, value);
Example
<script>
let andy ={ename:"Andrel"},
varun = {ename:"Varun"},
prijin={ename:"Prijin"}
console.log(empJobs)
</script>
get()
This function returns value if the key is matched or returns undefined if the key is not
found.
296
ES6
Syntax
The syntax for get() is mentioned below, where, key is the key of the element to return
from the Map object.
map_name.get(key)
Example
<script>
let andy ={ename:"Andrel"},
varun = {ename:"Varun"},
prijin={ename:"Prijin"}
console.log(empJobs.size)
</script>
Developer
2
297
ES6
has()
This function returns true if an element with the specified key exists; otherwise it returns
false.
Syntax
The syntax for has() is given below, where, key is the key of the element to test for
presence.
myMap.has(key)
Example
<script>
let andy ={ename:"Andrel"},
varun = {ename:"Varun"},
prijin={ename:"Prijin"}
console.log(empJobs.has(prijin))
console.log(empJobs.size)
</script>
false
2
298
ES6
keys()
This function returns an iterator that contains the keys for each element in the map
object.
Syntax
The syntax for keys() is given below:
map_name.keys()
Example
<script>
let andy ={ename:"Andrel"},
varun = {ename:"Varun"},
prijin={ename:"Prijin"}
Andrel
Varun
299
ES6
values()
This function returns an iterator that contains the values for each element in the map
object.
Syntax
The syntax for values() is as follows:
map_name.values()
Example
<script>
let andy ={ename:"Andrel"},
varun = {ename:"Varun"},
prijin={ename:"Prijin"}
Software Architect
Developer
300
ES6
entries()
This function returns an iterator that contains the key-value pairs for each element in the
Map.
Syntax
The syntax for entries() is as given below:
map_name.entries()
Example
<script>
let andy ={ename:"Andrel"},
varun = {ename:"Varun"},
prijin={ename:"Prijin"}
</script>
301
ES6
delete()
This function is used to remove the specified element from a Map object.
Syntax
The syntax for delete() is given below, where, key is the key of the element to remove
from the map.
map_name.delete(key)
where,
Example
<script>
let andy ={ename:"Andrel"},
varun = {ename:"Varun"},
prijin={ename:"Prijin"}
</script>
302
ES6
WeakMap
WeakMap is a small subset of map. Keys are weakly referenced, so it can be non-
primitive only. If there are no reference to the object keys, it will be subject to garbage
collection.
not iterable
every key is object type
The WeakMap will allow garbage collection if the key has no reference.
Syntax
The syntax for WeakMap is stated below:
new WeakMap([iterable])
Example 1.
<script>
</script>
Example 2.
<script>
empMap.set(e1,1001);
empMap.set(e2,1002);
empMap.set(e3,1003);
console.log(empMap)
console.log(empMap.get(e2))
303
ES6
console.log(empMap.has(e2))
empMap.delete(e1)
console.log(empMap)
</script>
Set
A set is an unordered collection of unique values. This data structure can contain values
of primitive and object types.
Syntax
The syntax for Set is given below:
new Set([iterable])
new Set()
Example
<script>
let names= new Set(['A','B','C','D']);
console.log(names)
</script>
304
ES6
Syntax
The syntax for checking the size of a set is mentioned below:
set.size
Example
<script>
let names= new Set(['A','B','C','D']);
console.log(names.size)
</script>
Iterating a Set
We can use the forEach and for..of loops to iterate through a Set. This is shown in the
example below:
Example
<script>
console.log('for of..')
305
ES6
}
</script>
forEach
A
B
C
D
for of..
A
B
C
D
add()
This function is used to add an element to the set.
Syntax
The below mentioned syntax is for add(), where, value is the value to add to the Set.
set_name.add(value)
Example
<script>
306
ES6
{{…}, {…}}
{"Varun", "Prijin", "Navya", "Kannan", "Raj", …}
has()
Returns true if element found, otherwise it returns false.
Syntax
Below mentioned is the syntax for has(), where, value is the value to search for in the
Set.
set_name.has(value)
Example
<script>
307
ES6
console.log(names.has('B'))
</script>
true
delete
This function is used to delete a specific element from the Set.
Syntax
The syntax mentioned below is for delete, where, value is the value to delete from the
Set.
set_name.delete(value)
Example
<script>
</script>
clear()
This function clears all elements from the Set.
Syntax
Below mentioned syntax is for clear().
set_name.clear()
308
ES6
Example
<script>
</script>
WeakSet
A Weakset holds objects weakly, that means object stored in a WeakSet are subject to
garbage collection, if they are not referenced. WeakSets are not iterable and do not have
the get method.
<script>
let e1 = {ename:'A'}
let e2 ={ename:'B'}
let e3 ={ename:'C'}
console.log(emps)
console.log(emps.has(e1))
emps.delete(e1);
console.log(emps)
</script>
309
ES6
310
30. ES6 − Promises ES6
Promise Syntax
The Syntax related to promise is mentioned below where, p is the promise
object, resolve is the function that should be called when the promise executes
successfully and reject is the function that should be called when the promise encounters
an error.
Example
The example given below shows a function add_positivenos_async() which adds two
numbers asynchronously. The promise is resolved if positive values are passed. The
promise is rejected if negative values are passed.
<script>
311
ES6
})
return p;
}
add_positivenos_async(10, 20)
.then(successHandler) // if promise resolved
.catch(errorHandler);// if promise rejected
add_positivenos_async(-10, -20)
.then(successHandler) // if promise resolved
.catch(errorHandler);// if promise rejected
function errorHandler(err) {
console.log('Handling error', err)
}
function successHandler(result) {
console.log('Handling success', result)
console.log('end')
</script>
end
Handling success 30
Handling error NOT_Postive_Number_Passed
Promises Chaining
Promises chaining can be used when we have a sequence of asynchronous tasks to
be done one after another. Promises are chained when a promise depends on the result
of another promise. This is shown in the example below:
Example
312
ES6
<script>
})
return p;
}
add_positivenos_async(10,20)
.then(function(result){
console.log("first result",result)
return add_positivenos_async(result,result)
}).then(function(result){
console.log("second result",result)
return add_positivenos_async(result,result)
}).then(function(result){
console.log("third result",result)
})
console.log('end')
</script>
end
313
ES6
first result 30
second result 60
third result 120
Some common used methods of the promise object are discussed below in detail:
promise.all()
This method can be useful for aggregating the results of multiple promises.
Syntax
The syntax for the promise.all() method is mentioned below, where, iterable is an
iterable object. E.g. Array.
Promise.all(iterable);
Example
The example given below executes an array of asynchronous
operations [add_positivenos_async(10,20),add_positivenos_async(30,40),add_
positivenos_async(50,60)]. When all the operations are completed, the promise is fully
resolved.
<script>
})
return p;
}
//Promise.all(iterable)
314
ES6
Promise.all([add_positivenos_async(10,20),add_positivenos_async(30,40),add_posi
tivenos_async(50,60)])
.then(function(resolveValue){
console.log(resolveValue[0])
console.log(resolveValue[1])
console.log(resolveValue[2])
console.log('all add operations done')
})
.catch(function(err){
console.log('Error',err)
})
console.log('end')
</script>
end
30
70
110
all add operations done
promise.race()
This function takes an array of promises and returns the first promise that is settled.
Syntax
The syntax for the promise.race() function is mentioned below, where, iterable is an
iterable object. E.g. Array.
Promise.race(iterable)
Example
The example given below takes an
array [add_positivenos_async(10,20),add_positivenos_async(30,40)] of
asynchronous operations.
The promise is resolved whenever any one of the add operation completes. The promise
will not wait for other asynchronous operations to complete.
<script>
315
ES6
})
return p;
}
//Promise.race(iterable)
Promise.race([add_positivenos_async(10,20),add_positivenos_async(30,40)])
.then(function(resolveValue){
console.log('one of them is done')
console.log(resolveValue)
}).catch(function(err){
console.log("Error",err)
})
console.log('end')
</script>
end
one of them is done
30
Promises are a clean way to implement async programming in JavaScript (ES6 new
feature). Prior to promises, Callbacks were used to implement async programming. Let’s
begin by understanding what async programming is and its implementation, using
Callbacks.
316
ES6
Understanding Callback
A function may be passed as a parameter to another function. This mechanism is termed
as a Callback. A Callback would be helpful in events.
<script>
function notifyAll(fnSms, fnEmail)
{
console.log('starting notification process');
fnSms();
fnEmail();
}
notifyAll(function()
{
console.log("Sms send ..");
}, function()
{
console.log("email send ..");
});
console.log("End of script"); //executes last or blocked by other methods
</script>
In the notifyAll() method shown above, the notification happens by sending SMS and by
sending an e-mail. Hence, the invoker of the notifyAll method has to pass two functions
as parameters. Each function takes up a single responsibility like sending SMS and sending
an e-mail.
In the code mentioned above, the function calls are synchronous. It means the UI thread
would be waiting to complete the entire notification process. Synchronous calls become
blocking calls. Let's understand non-blocking or async calls now.
Understanding AsyncCallback
Consider the above example.
317
ES6
A callback function
The number of seconds after which the method will be called
In this case, the notification process has been wrapped with timeout. Hence, it will take a
two seconds delay, set by the code. The notifyAll() will be invoked and the main thread
goes ahead like executing other methods. Hence, the notification process will not block
the main JavaScript thread.
<script>
function notifyAll(fnSms, fnEmail)
{
setTimeout(function()
{
console.log('starting notification process');
fnSms();
fnEmail();
}, 2000);
}
notifyAll(function()
{
console.log("Sms send ..");
},
function()
{
console.log("email send ..");
});
console.log("End of script"); //executes first or not blocked by others
</script>
End of script
starting notification process
Sms send ..
318
ES6
Email send ..
<script>
setTimeout(function()
{
console.log("one");
setTimeout(function()
{
console.log("two");
setTimeout(function()
{
console.log("three");
}, 1000);
}, 1000);
}, 1000);
</script>
ES6 comes to your rescue by introducing the concept of promises. Promises are
"Continuation events" and they help you execute the multiple async operations together
in a much cleaner code style.
Example
Let's understand this with an example. Following is the syntax for the same.
else
reject(Error("It broke"));
});
319
ES6
The first step towards implementing the promises is to create a method which will use the
promise. Let’s say in this example, the getSum() method is asynchronous i.e., its
operation should not block other methods’ execution. As soon as this operation completes,
it will later notify the caller.
The following example (Step 1) declares a Promise object ‘var promise’. The Promise
Constructor takes to the functions first for the successful completion of the work and
another in case an error happens.
The promise returns the result of the calculation by using the resolve callback and passing
in the result, i.e., n1+n2.
If the getSum() encounters an error or an unexpected condition, it will invoke the reject
callback method in the Promise and pass the error information to the caller.
The second step details the implementation of the caller (STEP 2).
The caller should use the ‘then’ method, which takes two callback methods - first for
success and second for failure. Each method takes one parameter, as shown in the
following code.
getSum(5, 6)
.then(function (result) {
320
ES6
console.log(result);
},
function (error) {
console.log(error);
});
11
Since the return type of the getSum() is a Promise, we can actually have multiple ‘then’
statements. The first 'then' will have a return statement.
getSum(5, 6)
.then(function(result)
{
console.log(result);
returngetSum(10, 20); // this returns another promise
},
function(error)
{
console.log(error);
})
.then(function(result)
{
console.log(result);
}, function(error)
{
console.log(error);
});
11
30
The following example issues three then() calls with getSum() method.
<script>
function getSum(n1, n2)
321
ES6
varisAnyNegative = function()
{
return n1 < 0 || n2 < 0;
}
var promise = new Promise(function(resolve, reject)
{
if (isAnyNegative())
{
reject(Error("Negatives not supported"));
}
resolve(n1 + n2);
});
return promise;
}
getSum(5, 6)
.then(function(result)
{
console.log(result);
returngetSum(10, 20); //this returns another Promise
},
function(error)
{
console.log(error);
})
322
ES6
.then(function(result)
{
console.log(result);
returngetSum(30, 40); //this returns another Promise
}, function(error)
{
console.log(error);
})
.then(function(result)
{
console.log(result);
}, function(error)
{ console.log(error);
});
console.log("End of script ");
</script>
The program displays ‘end of script’ first and then results from calling getSum() method,
one by one.
End of script
11
30
70
This shows getSum() is called in async style or non-blocking style. Promise gives a nice
and clean way to deal with the Callbacks.
323
31. ES6 − Modules ES6
Introduction
Consider a scenario where parts of JavaScript code need to be reused. ES6 comes to your
rescue with the concept of Modules.
A module organizes a related set of JavaScript code. A module can contain variables and
functions. A module is nothing more than a chunk of JavaScript code written in a file.
By default, variables and functions of a module are not available for use. Variables and
functions within a module should be exported so that they can be accessed from within
other files. Modules in ES6 work only in strict mode. This means variables or functions
declared in a module will not be accessible globally.
Exporting a Module
The export keyword can be used to export components in a module. Exports in a module
can be classified as follows:
Named Exports
Default Exports
Named Exports
Named exports are distinguished by their names. There can be several named exports in
a module. A module can export selected components using the syntax given below:
Syntax 1
Syntax 2
export {component1,component2,....,componentN}
324
ES6
Default Exports
Modules that need to export only a single value can use default exports. There can be only
one default export per module.
Syntax
However, a module can have a default export and multiple named exports at the same
time.
Importing a Module
To be able to consume a module, use the import keyword. A module can have
multiple import statements.
Syntax
However, while importing named exports, they can be renamed using the as keyword.
Use the syntax given below:
All named exports can be imported onto an object by using the asterisk * operator.
Syntax
325
ES6
export {company,getCompany,setCompany}
Step 2: Create a file company2.js. This file consumes components defined in the
company1.js file. Use any of the following approaches to import the module.
Approach 1:
console.log(company)
console.log(getCompany())
Approach 2:
console.log(x)
console.log(y())
Approach 3:
console.log(myCompany.getCompany())
console.log(myCompany.company)
To execute both the modules we need to make a html file as shown below and run this in
live server. Note that we should use the attribute type="module" in the script tag.
<!DOCTYPE html>
<html lang="en">
<head>
326
ES6
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="./company2.js" type="module"></script>
</body>
</html>
TutorialsPoint
TUTORIALSPOINT
Default Export
Step 1: Create a file company1.js and add the following code:
let company = {
getName:function(){
return name
},
setName:function(newName){
name =newName
}
Step 2: Create a file company2.js. This file consumes the components defined in the
company1.js file.
console.log(c.getName())
327
ES6
c.setName('Google Inc')
console.log(c.getName())
To execute both the modules we need to make an html file as shown below and run this
in live server. Note that we should use the attribute type="module" in the script tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="./company2.js" type="module"></script>
</body>
</html>
TutorialsPoint
Google Inc
//named export
export let name = 'TutorialsPoint'
let company = {
getName:function(){
return name
},
setName:function(newName){
name =newName
}
328
ES6
//default export
export default company
Step 2: Create a file company2.js. This file consumes the components defined in the
company1.js file. Import the default export first, followed by the named exports.
console.log(name)
console.log(c.getName())
c.setName("Mohtashim")
console.log(c.getName())
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="company2.js" type="module"></script>
</body>
</html>
TutorialsPoint
TutorialsPoint
Mohtashim
329
ES6
330
32. ES6 − Error Handling ES6
There are three types of errors in programming: Syntax Errors, Runtime Errors, and
Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript. When a syntax error occurs
in JavaScript, only the code contained within the same thread as the syntax error is
affected and the rest of the code in other threads get executed assuming nothing in them
depends on the code containing the error.
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation). Exceptions also affect the thread in which they occur, allowing
other JavaScript threads to continue normal execution.
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not
the result of a syntax or runtime error. Instead, they occur when you make a mistake in
the logic that drives your script and you do not get the result as expected.
You cannot catch those errors, because it depends on your business requirement, what
type of logic you want to put in your program.
JavaScript throws instances of the Error object when runtime errors occur. The following
table lists predefined types of the Error object.
331
ES6
Throwing Exceptions
An error (predefined or user defined) can be raised using the throw statement. Later
these exceptions can be captured and you can take an appropriate action. Following is the
syntax for the same.
Exception Handling
Exception handling is accomplished with a try...catch statement. When the program
encounters an exception, the program will terminate in an unfriendly fashion. To safeguard
against this unanticipated error, we can wrap our code in a try...catch statement.
The try block must be followed by either exactly one catch block or one finally block (or
one of both). When an exception occurs in the try block, the exception is placed in e and
the catch block is executed. The optional finally block executes unconditionally after
try/catch.
try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
332
ES6
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
Example
var a = 100;
var b = 0;
try
{
if (b == 0 )
{
throw(“Divide by zero error.”);
}
else
{
var c = a / b;
}
}
catch( e )
{
console.log("Error: " + e );
}
Output
The following output is displayed on successful execution of the above code.
Note: You can raise an exception in one function and then you can capture that exception
either in the same function or in the caller function using a try...catch block.
333
ES6
Example
<html>
<head>
<script type="text/javascript">
window.onerror = function () {
document.write ("An error occurred.");
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
Output
The following output is displayed on successful execution of the above code.
The onerror event handler provides three pieces of information to identify the exact nature
of the error:
Error message: The same message that the browser would display for the given
error.
Line number: The line number in the given URL that caused the error.
334
ES6
Example
<html>
<head>
<script type="text/javascript">
window.onerror = function (msg, url, line) {
document.write ("Message : " + msg );
document.write ("url : " + url );
document.write ("Line number : " + line );
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
Custom Errors
JavaScript supports the concept of custom errors. The following example explains the
same.
console.log(e.name);
console.log(e.message); // 'Default Message'
}
335
ES6
CustomError
Error raised with default message
try {
throw new MyError('Printing Custom Error message');
} catch (e) {
console.log(e.name);
console.log(e.message);
}
CustomError
Printing Custom Error message
336
33. ES6 — Object Extensions ES6
String extension
Some popular methods added to the String object in ES6 are:
String.prototype.startsWith()
It determines whether a string begins with the characters of a specified string. This
function returns true or false.
Syntax
The syntax given below is for String.prototype.startsWith(), where, searchString is
the characters to be searched for at the start of this string. position is an optional
parameter. It represents the position in this string at which to begin searching for
searchString. The default value is 0.
str.startsWith(searchString[, position])
Example
let company='TutorialsPoint'
console.log(company.startsWith('Tutorial'))
console.log(company.startsWith('orial',3)) // 3 is index
true
true
String.prototype.endsWith()
This function determines whether a string ends with the characters of a specified string
and returns true or false.
Syntax
The syntax which is mentioned below is for String.prototype.endsWith(), where,
searchString is the characters to be searched for at the end of this string. length is an
optional parameter. It represents the length of string.
str.endsWith(searchString[, length])
Example
<script>
let company='TutorialsPoint'
console.log(company.endsWith('Point'));
console.log(company.endsWith('Tutor',5))//5 is length of string
</script>
true
true
338
ES6
String.prototype.includes()
This function determines whether one string may be found within another string.
Syntax
The following syntax is for String.prototype.includes(), where, searchString is a string
to be searched for within this string position is an optional parameter. It represents the
position in this string at which to begin searching for searchString. The default value is
0.
str.includes(searchString[, position])
Example
<script>
let company='TutorialsPoint'
console.log(company.includes('orial'))
console.log(company.includes('orial',4))
</script>
true
false
String.prototype.repeat()
This function constructs and returns a new string which contains the specified number of
copies of the string on which it was called, concatenated together.
Syntax
The below mentioned syntax is for the function String.prototype.repeat(), where,
count indicates the number of times to repeat the string in the newly-created string that
is to be returned.
str.repeat(count)
Example
<script>
let name="Kiran-"
console.log(name.repeat(3));
339
ES6
</script>
Kiran-Kiran-Kiran-
Regex extensions
In a regular expression, for example, /[A-Z]/g, the beginning and ending / are called
delimiters. Anything after the closing delimiter is called a modifier. ES6 adds a new
modifier /g where g stands for global. This match all instances of the pattern in a string,
not just one.
Example
The following example searches and returns all upper-case characters in the string.
<script>
let str = 'JJavascript is Fun to Work , very Fun '
let regex = /[A-Z]/g // g stands for global matches
let result = str.match(regex);
console.log(result)
</script>
340
ES6
Example
The following example performs a case insensitive global match. The example
replaces fun with enjoyable.
<script>
Number
Some popular methods added to the Number object in ES6 are:
341
ES6
Number.isFinite
Determines whether the passed value is a finite number. Returns true/false.
Syntax
The syntax mentioned below if for Number.isFinite, where, value has to be tested for
finiteness.
Example
<script>
console.log(Number.isFinite(Infinity))//false
console.log(Number.isFinite(-Infinity))//false
console.log(Number.isFinite(NaN))//false
console.log(Number.isFinite(123))//true
console.log(Number.isFinite('123')) // evaluates to false
console.log(isFinite('123')) // evaluates to true,global function
</script>
false
false
false
true
false
true
Number.isNaN
This function returns true if the given value is Not-a-Number (NaN) and its type is
Number; otherwise, it returns false.
Syntax
Below mentioned is the syntax for the function Number.isNaN, where value is the
number to determine if it is a NaN.
342
ES6
Example
<script>
console.log(Number.isNaN('123'))//false
console.log(Number.isNaN(NaN))//true
console.log(Number.isNaN(0/0))//true
</script>
false
true
true
Number.parseFloat
A floating-point number parsed from the given value. If the value cannot be converted to
a number, NaN is returned.
Syntax
The syntax given below is for the function Number.parseFloat, where string is the value
parse.
Number.parseFloat(string)
Example
<script>
console.log(Number.parseFloat('10.3meters'));
console.log(Number.parseFloat('abc10.3xyz'));
</script>
10.3
NaN
Number.parseInt
Parses a string argument and returns an integer of the specified radix or base.
343
ES6
Syntax
Given below is the syntax for the function Number.parselnt, where, string is the value
to parse radix is an integer between 2 and 36 that represents the base.
Number.parseInt(string,[ radix ])
Example
<script>
console.log(Number.parseInt('10meters'))
console.log(Number.parseInt('abc10meters'))
</script>
10
NaN
Math
Some popular methods added to the Math object in ES6 are:
Math.sign()
This function returns the sign of a number, indicating whether the number is positive,
negative or zero.
Syntax
The syntax mentioned herewith is for the function Math.sign(), where, X − represents a
number.
Math.sign( x ) ;
Example
<script>
344
ES6
console.log(Math.sign(-Infinity)) // console.log(Math.sign(-10))
// -1
console.log(Math.sign(0)) // 0
console.log(Math.sign(Infinity)) // 1
console.log(Math.sign(10)) // 1
console.log(Math.sign('N')) // NaN
</script>
-1
0
1
1
NaN
Math.trunc()
This function returns the integer part of a number by removing any fractional digits.
Syntax
The syntax stated below is for the function Math.trunc(), where, X − represents a
number.
Math.trunc( x ) ;
Example
<script>
console.log(Math.trunc(-3.5)) // -3
console.log(Math.trunc(-3.6)) // -3
console.log(Math.trunc(3.5)) // 3
console.log(Math.trunc(3.6)) // 3
</script>
-3
-3
345
ES6
3
3
Array.copyWithin
This function shallow copies part of an array to another location in the same array and
returns it without modifying its length.
Syntax
The syntax stated below is for the array method “.copyWithin()”, where,
target: Zero-based index at which to copy the sequence to. If negative, target will
be counted from the end.
start: This is an optional parameter. Zero-based index at which to start copying
elements from. If negative, start will be counted from the end. If start is omitted,
copyWithin will copy from index 0.
346
ES6
Example
<script>
//copy with in
let marks = [10,20,30,40,50,60]
console.log(marks.copyWithin(0,2,4)) //destination,source start,source
end(excluding)
console.log(marks.copyWithin(2,4))//destination,source start,(till
length)
</script>
Array.entries
This function returns a new Array Iterator object that contains the key/value pairs for each
index in the array.
Syntax
The syntax given below is for the array method entries().
array.entries()
Example
<script>
//enties
let cgpa_list = [7.5,8.5,6.5,9.5]
347
ES6
</script>
7.5
8.5
6.5
9.5
Array.find
This function returns the value of the first element in the array that satisfies the provided
testing function. Otherwise undefined is returned.
Syntax
Given below is the syntax for the array method find(), where, thisArg is an optional
object to use as this when executing the callback and callback is the function to execute
on each value in the array, taking three arguments as follows:
Example
<script>
//find
const products = [{name:'Books',quantity:10},
{name:'Pen',quantity:20},
{name:"Books",quantity:30}
]
console.log( products.find(p=>p.name==="Books"))
348
ES6
</script>
Array.fill
This function fills all the elements of an array from a start index to an end index with a
static value. It returns the modified array.
Syntax
The syntax given herewith is for the array method fill(), where,
Example
<script>
//fill
console.log(nosArr.fill(0,1)) // [10,0,0,0]
console.log(nosArr.fill(0))
</script>
[10, 0, 0, 40]
[10, 0, 0, 0]
[0, 0, 0, 0]
349
ES6
Array.of
This function creates a new array instance from a variable number of arguments,
regardless of number or type of the arguments.
Syntax
The syntax mentioned below is for the array method of(), where, elementN are Elements
of which to create the array.
Example
<script>
//Array.of
console.log(Array.of(10))
console.log(Array.of(10,20,30))
console.log(Array(3))
console.log(Array(10,20,30))
</script>
[10]
Array.from
This function creates a shallow copy from an array like or iterable object.
Syntax
The syntax mentioned below is for an array method from(), where,
350
ES6
Example
<script>
//Array.from
//iterate over an object
const obj_arr ={
length:2,
0:101,
1:'kannan'
}
console.log(obj_arr)
const arr = Array.from(obj_arr)
console.log(arr)
for(const element of arr){
console.log(element);
}
console.log(Array.from('Javascript'))
let setObj = new Set(['Training',10,20,20,'Training'])
console.log(Array.from(setObj))
console.log(Array.from([10,20,30,40],n=>n+1))
</script>
351
ES6
Object
Methods related to Object function are mentioned below in the table along with the
respective description.
Object.is
This function determines whether two values are the same value.
Syntax
The syntax which is given below is for an object method is(), where,
Object.is(value1, value2);
Example
<script>
console.log(Object.is(emp1.ename,emp2.ename))
</script>
352
ES6
true
Object.setPrototypeOf
With the help of this function, we can set the prototype of a specified object to another
object or null.
Syntax
In this syntax, obj is the object which is to have its prototype set and prototype is the
object's new prototype (an object or null).
Object.setPrototypeOf(obj, prototype)
Example
<script>
let emp ={name:'A',location:'Mumbai',basic:5000}
let mgr = {name:'B'}
console.log(emp.__proto__ == Object.prototype)
console.log(mgr.__proto__ == Object.prototype)
console.log(mgr.__proto__ ===emp.__proto__)
Object.setPrototypeOf(mgr,emp)
console.log(mgr.__proto__ == Object.prototype) //false
console.log(mgr.__proto__ === emp)
console.log(mgr.location,mgr.basic)
</script>
true
true
true
false
true
Mumbai 5000
353
ES6
Object.assign
Copy the values of all enumerable own properties from one or more source objects to a
target object. It will return the target object.
Syntax
In the syntax given below target is the target object and sources is the source object(s).
Object.assign(target, ...sources)
Example
<script>
//Object.assign()
let obj1 ={x:10},
obj2={y:20},
obj3={z:30}
Object.assign(obj1,obj2,obj3)
console.log("obj 1",obj1)
</script>
354
34. ES6 — Reflect API ES6
ES6 introduces Reflect Application Programming Interface (Reflect API) and Proxy API that
supports meta programming.
Some commonly used methods of the Reflect object are given below:
355
ES6
Reflect.apply()
This function calls a target function with arguments as specified by the args parameter.
Syntax
The syntax given herewith is for apply(), where,
Example
The following example defines a function that calculates and returns the area of a
rectangle.
<script>
const areaOfRectangle = function(width,height){
return `area is ${width*height} ${this.units}`
}
const thisValue = {
units:'Centimeters'
}
const argsList = [10,20]
const result = Reflect.apply(areaOfRectangle,thisValue,argsList)
console.log(result)
356
ES6
</script>
Reflect.construct()
This method acts as the new operator and is equivalent to calling new target(...args).
Syntax
The syntax given below is for the function construct(), where,
Example
The following example creates a class Student with a property fullName. The constructor
of the class takes firstName and lastName as parameters. An object of the class Student
is created using reflection as shown below.
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
const s1 = Reflect.construct(Student,args)
console.log(s1.fullName)
</script>
Mohammad : Mohtashim
Reflect.get()
This is a function that returns the value of properties.
Syntax
The syntax for the function get() is given below, where,
Example
The following example creates an instance of the class Student using reflection and fetches
the properties of the instance using the Reflect.get() method.
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
const args = ['Tutorials','Point']
const s1 = Reflect.construct(Student,args)
358
ES6
console.log('fullname is ',Reflect.get(s1,'fullName'))
console.log('firstName is ',Reflect.get(s1,'firstName'))
</script>
Reflect.set()
This is a function that assign values to properties. It returns a Boolean that is true if the
update was successful.
Syntax
The syntax which is mentioned below is for the function set(), where,
target is the target object on which to get the property.
propertyKey is the name of the property to get value to set.
receiver is The value of this provided for the call to target if a setter is
encountered. This is an optional argument.
Example
The following example creates an instance of the class Student using reflection and sets
the value of the instance’s properties using the Reflect.set() method.
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
359
ES6
fullname is Tutorials :
fullname is Tutorials : Point
Reflect.has()
This is the in operator as a function which returns a boolean indicating whether an own or
inherited property exists.
Syntax
Given below is the syntax for the function has(), where,
target is the target object in which to look for the property.
propertyKey is the name of the property to check.
Reflect.has(target, propertyKey)
Example
The following example creates an instance of the class Student using reflection and
verifies if the properties exist using the Reflect.has() method.
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
360
ES6
true
true
false
361
35. ES6 — Proxy API ES6
Sr No Terminology Description
Syntax
The syntax stated below is for the Proxy API, where, target can be any sort of object like
array, function or another proxy and handler is an object whose properties are functions.
This defines the behavior of the proxy.
362
ES6
Handler Methods
The handler object contains traps for Proxy. All traps are optional. If a trap has not been
defined, the default behavior is to forward the operation to the target. Some common
handler methods are as follows:
Sr No Method Description
Example: handler.apply()
The following example defines a function rectangleArea, which takes width and height
as parameters and returns the area of the rectangle. The program creates a proxy and
defines a handler object for the rectangleArea function. This handler object verifies the
number of parameters passed to the function before the function is executed. The handler
object throws an error if two parameters are not passed to the function.
<script>
function rectangleArea(width,height){
return width*height;
}
const handler = {
apply:function(target,thisArgs,argsList){
console.log(argsList);
//console.log(target)
if(argsList.length ==2){
return Reflect.apply(target,thisArgs,argsList)
363
ES6
[10, 20]
area is 200
[10]
Uncaught Invalid no of arguments to calculate
Example: handler.construct()
The following example defines a class Student with a constructor and a getter method.
The constructor takes firstName and lastName as parameters. The program creates a
proxy and defines a handler object to intercept the constructor. The handler object verifies
the number of parameters passed to the constructor. The handler object throws an error
if exactly two parameters are not passed to the constructor.
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
const handler = {
364
ES6
construct:function(target,args){
if(args.length==2)
{
return Reflect.construct(target,args);
}
else throw 'Please enter First name and Last name'
}
}
</script>
kannan : sudhakaran
Uncaught Please enter First name and Last name
365
ES6
Example:handler.get()
The following example defines a class Student with a constructor and a custom getter
method, fullName. The custom getter method returns a new string by concatenating the
firstName and lastName. The program creates a proxy and defines a handler object
intercepts whenever the properties firstName, lastName and fullName are accessed. The
property values will be returned in uppercase.
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
const handler = {
get: function(target,property){
return Reflect.get(target,property).toUpperCase();
}
}
366
ES6
TUTORIALS : POINT
TUTORIALS
POINT
Example:handler.set()
The following example defines a class Student with a constructor and a custom getter
method, fullName. The constructor takes firstName and lastName as parameters. The
program creates a proxy and defines a handler object which intercepts all set operations
on firstName and lastName. The handler object throws an error if the length of the property
value is not greater than 2.
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
const handler = {
set: function(target,property,value){
if(value.length>2){
return Reflect.set(target,property,value);
}
else
{ throw 'string length should be greater than 2'
}
}
}
367
ES6
</script>
Tutorials : Point
Test : Point
Uncaught string length should be greater than 2
Example:handler.has()
The following example defines a class Student with a constructor that takes firstName
and lastName as parameters. The program creates a proxy and defines a handler object.
The has() method of the handler object is called whenever the in operator is used.
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
}
const handler = {
has: function(target,property){
console.log('Checking for '+property+' in the object')
return Reflect.has(target,property)
368
ES6
}
}
369
36. ES6 − Validations ES6
Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by the client was
incorrect or was simply missing, the server would have to send all the data back to the
client and request that the form be resubmitted with the correct information. This was
really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate the form's data on the client's computer before
sending it to the web server. Form validation generally performs two functions.
Basic Validation: First of all, the form must be checked to make sure all the
mandatory fields are filled in. It would require just a loop through each field in the
form and check for data.
Data Format Validation: Secondly, the data that is entered must be checked for
correct form and value. Your code must include appropriate logic to test the
correctness of data.
Example
We will take an example to understand the process of validation. Here is a simple form in
html format.
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
370
ES6
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
371
ES6
Output
The following output is displayed on successful execution of the above code.
<script type="text/javascript">
<!--
// Form validation code will come here. function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" ); document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ; return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
372
ES6
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ; return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" ); return false;
}
return( true );
}
//-->
</script>
The following example shows how to validate an entered email address. An email address
must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character
of the email address, and the last dot must at least be one character after the ‘@’ sign.
Example
Try the following code for email validation.
<script type="text/javascript">
<!--
function validateEmail()
{
var emailID = document.myForm.EMail.value; atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf("."); if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
} //-->
</script>
373
37. ES6 − Animation ES6
You can use JavaScript to create a complex animation having, but not limited to, the
following elements:
Fireworks
Fade effect
Roll-in or Roll-out
Page-in or Page-out
Object movements
JavaScript can be used to move a number of DOM elements (<img />, <div>, or any other
HTML element) around the page according to some sort of pattern determined by a logical
equation or function.
setTimeout (function, duration) - This function calls the function after duration
milliseconds from now.
setInterval (function, duration) - This function calls the function after every
duration milliseconds.
JavaScript can also set a number of attributes of a DOM object including its position on
the screen. You can set the top and the left attribute of an object to position it anywhere
on the screen. Following is the syntax for the same.
or
374
ES6
Manual Animation
So let's implement one simple animation using DOM object properties and JavaScript
functions as follows. The following list contains different DOM methods.
• We are using the JavaScript function getElementById() to get a DOM object and
then assigning it to a global variable imgObj.
Example
Try the following example.
<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null; function init(){
imgObj = document.getElementById('myImage'); imgObj.style.position=
'relative'; imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
window.onload =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click button below to move the image to right</p>
<input type="button" value="Click Me" onclick="moveRight();" />
</form></body></html>
It is not possible to show the result, i.e., the animation in this tutorial.
375
ES6
Automated Animation
In the above example, we saw how an image moves to the right with every click. We can
automate this process by using the JavaScript function setTimeout() as follows.
Here we have added more methods. So, let's see what is new here.
• We have added a new function stop() to clear the timer set by setTimeout()
function and to set the object at its initial position.
Example
Try the following example code.
<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null; var animate ; function init(){
imgObj = document.getElementById('myImage'); imgObj.style.position=
'relative'; imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px'; animate =
setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){ clearTimeout(animate); imgObj.style.left = '0px';
}
window.onload =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type="button" value="Start" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
376
ES6
</form>
</body>
</html>
• At the time of loading this page, the ‘if’ statement checks for the existence of the
image object. If the image object is unavailable, this block will not be executed.
• The Image() constructor creates and preloads a new image object called image1.
• The src property is assigned the name of the external image file called
/images/html.gif.
• The # (hash mark) disables the link so that the browser does not try to go to a
URL when clicked. This link is an image.
• The onMouseOver event handler is triggered when the user's mouse moves onto
the link, and the onMouseOut event handler is triggered when the user's mouse
moves away from the link (image).
• When the mouse moves over the image, the HTTP image changes from the first
image to the second one. When the mouse is moved away from the image, the
original image is displayed.
• When the mouse is moved away from the link, the initial image html.gif will
reappear on the screen.
<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type="text/javascript">
<!--
if(document.images){
var image1 = new Image();
// Preload an image image1.src = "/images/html.gif";
var image2 = new Image();
// Preload second image image2.src = "/images/http.gif";
}
377
ES6
//-->
</script>
</head>
<body>
<p>Move your mouse over the image to see the result</p><a href="#"
onMouseOver="document.myImage.src=image2.src;"
onMouseOut="document.myImage.src=image1.src;">
<img name="myImage" src="/images/html.gif" />
</a>
</body>
</html>
378
38. ES6 − Multimedia ES6
The JavaScript navigator object includes a child object called plugins. This object is an
array, with one entry for each plug-in installed on the browser. The navigator.plugins
object is supported only by Netscape, Firefox, and Mozilla.
Example
The following example shows how to list down all the plug-ins installed in your browser.
<html>
<head>
<title>List of Plug-Ins</title>
</head>
<body>
<table border="1">
<tr><th>Plug-in Name</th><th>Filename</th><th>Description</th></tr>
<script LANGUAGE="JavaScript" type="text/javascript"> for (i=0;
i<navigator.plugins.length; i++) { document.write("<tr><td>");
document.write(navigator.plugins[i].name); document.write("</td><td>");
document.write(navigator.plugins[i].filename);
document.write("</td><td>");
document.write(navigator.plugins[i].description);
document.write("</td></tr>");
}
</script>
</table>
</body></html>
379
ES6
Output
The following output is displayed on successful execution of the above code.
You can use these properties in a script to find out the installed plug-ins, and then using
JavaScript, you can play the appropriate multimedia file. Take a look at the following code.
<html>
<head>
<title>Using Plug-Ins</title>
</head>
<body>
<script language="JavaScript" type="text/javascript"> media =
navigator.mimeTypes["video/quicktime"]; if (media){
document.write("<embed src='quick.mov' height=100 width=100>");
} else{
document.write("<img src='quick.gif' height=100 width=100>");
}
</script>
</body>
380
ES6
</html>
Note: Here we are using HTML <embed> tag to embed a multimedia file.
Controlling Multimedia
Let us take a real example which works in almost all the browsers.
<html>
<head>
<title>Using Embeded Object</title>
<script type="text/javascript">
<!--
function play()
{
if (!document.demo.IsPlaying())
{
document.demo.Play();
}
}
function stop()
{
if (document.demo.IsPlaying()){
document.demo.StopPlay();
}
}
function rewind()
if (document.demo.IsPlaying()){
document.demo.StopPlay();
}
document.demo.Rewind();
}
//-->
</script>
</head>
<body>
<embed id="demo" name="demo"
381
ES6
382
39. ES6 − Debugging ES6
Every now and then, developers commit mistakes while coding. A mistake in a program
or a script is referred to as a bug.
The process of finding and fixing bugs is called debugging and is a normal part of the
development process. This chapter covers the tools and techniques that can help you with
debugging tasks.
Error Messages in IE
The most basic way to track down errors is by turning on the error information in your
browser. By default, the Internet Explorer shows an error icon in the status bar when an
error occurs on the page.
Double-clicking this icon takes you to a dialog box showing information about the specific
error that has occurred.
Since this icon is easy to overlook, Internet Explorer gives you the option to automatically
show the Error dialog box whenever an error occurs.
To enable this option, select Tools --> Internet Options --> Advanced tab and then
finally check the “Display a NotificationaboutEvery Script Error” box option as shown
in the following screenshot.
383
ES6
Unfortunately, since these browsers give no visual indication when an error occurs, you
must keep the Console open and watch for errors as your script executes.
Error Notifications
Error notifications that show up on the Console or through Internet Explorer dialog boxes
are the result of both syntax and runtime errors. These error notifications include the line
number at which the error occurred.
If you are using Firefox, then you can click on the error available in the error console to
go to the exact line in the script having the error.
Debugging a Script
There are various ways to debug your JavaScript. Following are some of the methods.
384
ES6
The most convenient validator for JavaScript is Douglas Crockford's JavaScript Lint, which
is available for free at Douglas Crockford's JavaScript Lint.
Simply visit the web page, paste your JavaScript (Only JavaScript) code into the text area
provided, and click the jslint button. This program will parse through your JavaScript
code, ensuring that all the variable and function definitions follow the correct syntax. It
will also check JavaScript statements, such as if and while, to ensure they too follow the
correct format
By examining the content and order of the alert() as they appear, you can examine the
health of your program very easily.
Once a script has been loaded into a debugger, it can be run one line at a time or instructed
to halt at certain breakpoints. Once the execution is halted, the programmer can examine
the state of the script and its variables in order to determine if something is amiss. You
can also watch variables for changes in their values.
The latest version of the Mozilla JavaScript Debugger (code-named Venkman) for both
Mozilla and Netscape browsers can be downloaded from:
http://www.hacksrus.com/~ginda/venkman.
• Use plenty of comments. Comments enable you to explain why you wrote the script
the way you did and to explain particularly the difficult sections of the code.
• Always use indentation to make your code easy to read. Indenting statements also
makes it easier for you to match up the beginning and ending tags, curly braces,
and other HTML and script elements.
385
ES6
• Write modular code. Whenever possible, group your statements into functions.
Functions let you group related statements, and test as well as reuse portions of
the code with minimal effort.
• Be consistent in the way you name your variables and functions. Try using names
that are long enough to be meaningful and that describe the contents of the
variable or the purpose of the function.
• Use consistent syntax when naming variables and functions. In other words, keep
them all lowercase or all uppercase; if you prefer Camel-Back notation, use it
consistently.
• Test long scripts in a modular fashion. In other words, do not try to write the entire
script before testing any portion of it. Write a piece and get it to work before adding
the next portion of the code.
• Use descriptive variable and function names and avoid using single character
names.
• Watch your quotation marks. Remember that quotation marks are used in pairs
around strings and that both quotation marks must be of the same style (either
single or double).
• Watch your equal signs. You should not use a single = for comparison purpose.
A prompt indicating that the debugger has started successfully will be launched.
To apply a breakpoint at a specified location, call the debugger in the source code as shown
in the following code.
// myscript.js
x = 5;
setTimeout(() => {
debugger;
console.log('world');
}, 1000);
console.log('hello');
386
ES6
Following is a set of stepping commands that one can use with Node.
Stepping
Description
Commands
cont,c Continue
next,n Next
step,s Step in
The debugger provides a plethora of features that allow us to launch configuration files,
apply/remove/disable and enable breakpoints, variable, or enable data inspection, etc.
387
40. ES6 − Image Map ES6
You can use JavaScript to create a client-side image map. Client-side image maps are
enabled by the usemap attribute for the <img /> tag and defined by special <map> and
<area> extension tags.
The image that is going to form the map is inserted into the page using the <img />
element as normal, except that it carries an extra attribute called usemap. The value of
the usemap attribute is the value of the name attribute on the <map> element, which you
are about to meet, preceded by a pound or a hash sign.
The <map> element actually creates the map for the image and usually follows directly
after the <img /> element. It acts as a container for the <area /> elements that actually
define the clickable hotspots. The <map> element carries only one attribute, the name
attribute, which is the name that identifies the map. This is how the <img /> element
knows which <map> element to use.
The <area> element specifies the shape and the coordinates that define the boundaries
of each clickable hotspot.
The following code combines imagemaps and JavaScript to produce a message in a text
box when the mouse is moved over different parts of an image.
<html>
<head>
<title>Using JavaScript Image Map</title><script type="text/javascript">
<!--
function showTutorial(name){
document.myform.stage.value = name
}
//-->
</script>
</head>
<body>
<form name="myform">
<input type="text" name="stage" size="20" />
</form>
<!-- Create Mappings -->
<img src="/images/usemap.gif" alt="HTML Map" border="0" usemap="#tutorials"/>
<map name="tutorials">
<area shape="poly" coords="74,0,113,29,98,72,52,72,38,27"
href="/perl/index.htm" alt="Perl Tutorial" target="_self"
onMouseOver="showTutorial('perl')" onMouseOut="showTutorial('')"/>
388
ES6
<area shape="rect"
coords="22,83,126,125"
href="/html/index.htm" alt="HTML Tutorial" target="_self"
onMouseOver="showTutorial('html')"
onMouseOut="showTutorial('')"/>
The following output is displayed on successful execution of the above code. You can feel
the map concept by placing the mouse cursor on the image object.
389
41. ES6 − Browsers ES6
Navigator Properties
There are several Navigator related properties that you can use in your webpage. The
following is a list of the names and its description.
Sr.
Property and Description
No.
appCodeName
1 This property is a string that contains the code name of the browser, Netscape
for Netscape and Microsoft Internet Explorer for Internet Explorer
appVersion
2 This property is a string that contains the version of the browser as well as other
useful information such as its language and compatibility
language
3 This property contains the two-letter abbreviation for the language that is used
by the browser. Netscape only
mimTypes[]
4 This property is an array that contains all MIME types supported by the client.
Netscape only
platform[]
5 This property is a string that contains the platform for which the browser was
compiled. "Win32" for 32-bit Windows operating systems
plugins[]
6 This property is an array containing all the plug-ins that have been installed
on the client. Netscape only
userAgent[]
7 This property is a string that contains the code name and version
of the browser. This value is sent to the originating server to
identify the client
390
ES6
Navigator Methods
There are several Navigator-specific methods. Here is a list of their names and
descriptions.
javaEnabled()
1 This method determines if JavaScript is enabled in the client. If JavaScript is
enabled, this method returns true; otherwise, it returns false
plugings.refresh
2 This method makes newly installed plug-ins available and populates the
plugins array with all new plug-in names. Netscape only
preference(name,value)
This method allows a signed script to get and set some Netscape preferences.
3
If the second parameter is omitted, this method will return the value of the
specified preference; otherwise, it sets the value. Netscape only
taintEnabled()
4
This method returns true if data tainting is enabled; false otherwise
Browser Detection
The following JavaScript code can be used to find out the name of a browser and then
accordingly an HTML page can be served to the user.
<html>
<head>
<title>Browser Detection Example</title>
</head>
<body>
<script type="text/javascript">
<!--
var userAgent = navigator.userAgent;
var opera = (userAgent.indexOf('Opera') != -1); var ie =
(userAgent.indexOf('MSIE') != -1); var gecko =
(userAgent.indexOf('Gecko') != -1); var netscape =
(userAgent.indexOf('Mozilla') != -1); var version = navigator.appVersion;
if (opera){
document.write("Opera based browser"); // Keep your opera specific URL here.
}else if (gecko){
391
ES6
392
42. ES7 — New Features ES6
Exponentiation Operator
ES7 introduces a new mathematical operator called exponentiation operator. This operator
is similar to using Math.pow() method. Exponentiation operator is represented by a double
asterisk **. The operator can be used only with numeric values. The syntax for using the
exponentiation operator is given below:
Syntax
The syntax for the exponentiation operator is mentioned below:
base_value ** exponent_value
Example
The following example calculates the exponent of a number using
the Math.pow() method and the exponentiation operator.
<script>
let base = 2
let exponent = 3
console.log('using Math.pow()',Math.pow(base,exponent))
console.log('using exponentiation operator',base**exponent)
</script>
using Math.pow() 8
using exponentiation operator 8
393
ES6
Array Includes
The Array.includes() method introduced in ES7 helps to check if an element is available in
an array. Prior to ES7, the indexof() method of the Array class could be used to verify if a
value exists in an array . The indexof() returns the index of the first occurrence of element
in the array if the data is found ,else returns -1 if the data doesn't exist.
Syntax
Array.includes(value)
OR
Array.includes(value,start_index)
The second syntax checks if the value exists from the index specified.
Example
The following example declares an array marks and uses the Array.includes() method to
verify if a value is present in the array.
<script>
394
ES6
</script>
395
43. ES8 — New Features ES6
Padding a String
ES8 introduces two string handling functions for padding a string. These functions can be
used to add space or any desired set of characters to the beginning and end of a string
value.
String. padStart()
This function pads the current string with a given input string repeatedly from the start,
till the current string reaches the given length. The syntax of the padStart() function is
given below:
Syntax
string_value.padStart(targetLength [, padString])
targetLength: A numeric value that represents the target length of the string after
padding. If the value of this parameter is lesser than or equal to the existing length
of the string, the string value is returned as it is.
Example
The following example declares a string variable, product_cost. The variable will be padded
with zeros from left until the total length of the string is seven. The example also illustrates
behaviour of the padStart() function, if no value is passed to the second parameter.
<script>
396
ES6
</script>
0001699
7
1699
7
String.padEnd()
This function pads the current string with a given input string repeatedly from the end, till
the current string reaches the specified length.
Syntax
string_value.padEnd(targetLength [, padString])
targetLength: A numeric value that represents the target length of the string
after padding. If the value of this parameter is lesser than or equal to the existing
length of the string, the string value is returned as it is.
397
ES6
Example
The following example declares a string variable, product_cost. The variable will be padded
with zeros from right until the total length of the string is seven. The example also
illustrates behaviour of the padStart() function, if no value is passed to the second
parameter.
<script>
//pad the string with x
let product_cost = '1699'.padEnd(7,'x')
console.log(product_cost)
console.log(product_cost.length)
1699xxx
7
1699
7
398
ES6
Trailing Commas
A trailing comma is simply a comma after the last item in a list. Trailing commas are also
known as final commas.
Example
The following example iterating an array with trailing commas using foreach loop.
<script>
let marks = [100,90,80,,]
console.log(marks.length)
console.log(marks)
4
[100, 90, 80, empty]
100
90
80
399
ES6
Example
The following example declares a function with trailing commas in the argument list.
<script>
function sumOfMarks(marks,){ // trailing commas are ignored
let sum=0;
marks.forEach(function(e){
sum+=e;
})
return sum;
}
console.log(sumOfMarks([10,20,30]))
console.log(sumOfMarks([1,2,3],))// trailing comma is ignored
</script>
60
6
400
ES6
Example
<script>
const student ={
firstName:'Kannan',
lastName:'Sudhakaran'
}
console.log(Object.entries(student))
console.log(Object.values(student))
</script>
[
["firstName", "Kannan"],
["lastName", "Sudhakaran"],
]
["Kannan", "Sudhakaran"]
Example
<script>
const marks = [10,20,30,40]
console.log(Object.entries(marks))
console.log(Object.values(marks))
</script>
401
ES6
[ ["0", 10],
["1", 20],
["2", 30],
["3", 40]
]
[10, 20, 30, 40]
Example
<script>
const student = {
firstName : 'Mohtashim',
lastName: 'Mohammad',
get fullName(){
return this.firstName + ':'+ this.lastName
}
}
console.log(Object.getOwnPropertyDescriptors(student))
</script>
402
ES6
Syntax
The syntax of async function with await is given below:
function_name().then(()=>{})
.catch(()=>{})
Consider an example that has an asynchronous function that takes two seconds to execute
and returns a string value. The function can be invoked in two ways as shown below:
Using promise.then()
Using aync/await.
The below code shows invoking the asynchronous function using the traditional ES6 syntax
- promise.then()
<script>
function fnTimeConsumingWork(){
return new Promise((resolve,reject)=>{
setTimeout(() => {
resolve('response is:2 seconds have passed')
}, 2000);
})
}
fnTimeConsumingWork().then(resp=>{
403
ES6
console.log(resp)
})
console.log('end of script')
</script>
end of script
response is:2 seconds have passed
The below code shows a cleaner way of invoking the asynchronous function using ES8
syntax - async/await
<script>
function fnTimeConsumingWork(){
return new Promise((resolve,reject)=>{
setTimeout(() => {
resolve('response is:2 seconds have passed')
}, 2000);
})
}
async function my_AsyncFunc(){
console.log('inside my_AsyncFunc')
const response = await fnTimeConsumingWork();// clean and readable
console.log(response)
}
my_AsyncFunc();
console.log("end of script")
</script>
inside my_AsyncFunc
end of script
response is:2 seconds have passed
404
ES6
<script>
function add_positivenos_async(n1, n2) {
let p = new Promise(function (resolve, reject) {
if (n1 >= 0 && n2 >= 0) {
//do some complex time consuming work
resolve(n1 + n2)
}
else
reject('NOT_Postive_Number_Passed')
})
return p;
}
}
addInSequence().then((r)=>console.log("Async :",r));
console.log('end')
</script>
405
ES6
end
first result 30
second result 60
third result 120
Async : Done Sequence
406
44. ES9 — New Features ES6
Here, we will learn about the new features in ES9. Let us begin by understanding about
the asynchronous generators.
Example
Following example shows an async generator which returns Promise on each call to
the next() method of generator.
<script>
async function* load(){
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}
let l = load();
l.next().then(r=>console.log(r))
l.next().then(r=>console.log(r))
l.next().then(r=>console.log(r))
l.next().then(r=>console.log(r))
</script>
407
ES6
The syntax for using the for await of loop is given below, where,
On each iteration a value of a different property is assigned to variable and a
variable may be declared with const, let, or var.
Example
The following example shows the use of for await of loop to iterate an async generator.
<script>
async function* load(){
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}
408
ES6
console.log('end of script')
</script>
end of script
1
2
3
Example
The following example iterates an array using the for await of loop.
<script>
async function fntest(){
for await (const val of [10,20,30,40]){
console.log(val)
}
}
fntest();
console.log('end of script')
</script>
end of script
10
20
30
40
Rest/Spread Properties
ES9 supports the use of Rest and Spread operators with Objects.
409
ES6
The following example shows the use of rest operator with an object. The value of age
property of student is copied into the age variable while the values of the remaining
properties are copied into the other variable using the rest syntax `...`.
<script>
const student = {
age:10,
height:5,
weight:50
}
</script>
10
{height: 5, weight: 50}
410
ES6
<script>
//spread operator
const obj1 = {a:10,b:20}
const obj2={c:30}
//clone obj1
const clone_obj={...obj1}
//combine obj1 and obj2
const obj3 = {...obj1,...obj2}
console.log(clone_obj)
console.log(obj3)
</script>
Promise: finally()
The finally() is executed whenever a promise is settled, regardless of its outcome. This
function returns a promise. It can be used to avoid code duplication in both the promise's
then() and catch() handlers.
Syntax
The below mentioned syntax is for the function finally().
promise.finally(function() {
});
promise.finally(()=> {
});
411
ES6
Example
The following example declares a async function that returns the square of a positive
number after a delay of 3 seconds. The function throws an error if a negative number is
passed. The statements in the finally block is executed in either case, whether the promise
is rejected or resolved.
<script>
let asyncSquareFn = function(n1){
console.log("End");
</script>
Start
End
//after 3 seconds
result is 100
412
ES6
inside finally
executes all the time
Unicode code point escape sequences are represented using "\u{}", for example
\u{2F}
Hexadecimal escape sequences are represented using "\x", for example \xA8
Octal literal escape sequences are represented using "" and followed by one or
more digits, for example \125
In ES2016 and earlier, if invalid escape sequences are used with tagged functions a Syntax
Error will be thrown as shown below:
However, unlike the earlier versions, ES9 parses the invalid unicode sequence
to undefined and does not throw an error. This is shown in the following example:
<script>
function myTagFn(str) {
return { "parsed": str[0] }
}
let result1 =myTagFn`\unicode1` //invalid unicode character
console.log(result1)
let result2 =myTagFn`\u2764\uFE0F`//valid unicode
console.log(result2)
</script>
{parsed: undefined}
{parsed: "❤️"}
413
ES6
Raw Strings
ES9 introduces a special property raw, available on the first argument to the tag function.
This property allows you to access the raw strings as they were entered, without
processing the escape sequences.
Example
<script>
function myTagFn(str) {
return { "Parsed": str[0], "Raw": str.raw[0] }
}
console.log(/Tutorials.Point/.test('Tutorials_Point')); //true
console.log(/Tutorials.Point/.test('Tutorials\nPoint')); //false
console.log(/Tutorials.Point/.test('Tutorials\rPoint')); //false
414
ES6
true
false
false
ES9 introduces a new flag - DotAllFlag (\s) that can be used with Regex to match line
terminators and emojis. This is shown in the following example:
console.log(/Tutorials.Point/s.test('Tutorials\nPoint'));
console.log(/Tutorials.Point/s.test('Tutorials\rPoint'));
true
true
(?<Name1>pattern1)
Example
const birthDatePattern = /(?<myYear>[0-9]{4})-(?<myMonth>[0-9]{2})/;
const birthDate = birthDatePattern.exec('1999-04');
console.log(birthDate.groups.myYear);
console.log(birthDate.groups.myMonth);
1999
04
415