Blog

  • ECMAScript 2016

    The ECMAScript 2016 version of JavaScript was released in 2016. Previously the old versions of JavaScript are named by numbers for example ES5 and ES6. Since 2016 the versions are named by the year they are released for example ECMAScript 2016, ECMAScript 17, etc. Lets discuss the featues added in ECMAScript 2016.

    New Features Added in ECMAScript 2016

    Here are the new methods, features, etc., added to the ECMAScript 2016 version of JavaScript.

    • Array includes() method
    • Exponentiation Operator (**)
    • Exponentiation Assignment Operator (**=)

    Here, we have explained each feature in detail.

    JavaScript Array includes() Method

    The JavaScript array includes() methods is used to check whether the array contains a particular element.

    Syntax

    The syntax of Array includes() method in JavaScript is as follows −

    arr.include(searchElement, fromIndex);

    Here arr is the original array, the searchElement is to be search from. The fromIndex is an optional argument if passed, the searching will start from the fromIndex index.

    Example

    In the below code, we use the array includes() method to check whether the watches array contains the ‘Noise’ brand.

    <html><body><div id ="output">Does watches array include Noise?</div><script>const watches =["Titan","Rolex","Noise","Fastrack","Casio"];
    
      document.getElementById("output").innerHTML += watches.includes("Noise");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Does watches array include Noise? true
    

    Example

    In the below code, we use the array includes() method to check whether the subjects array contains the 'Python' subject searching from index 1.

    <html><body><div id ="output">Does subjects array include Python fromIndex 1?</div><script>const subjects =["Java","JavaScript","Python","C","C++"];
    
      document.getElementById("output").innerHTML += subjects.includes("Python",1);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Does subjects array include Python fromIndex 1? true
    

    JavaScript Exponentiation Operator

    The JavaScript exponentiation operator is used to find the power of the first operand raised to the second operand.

    Syntax

    The syntax of expponentiation operator is as follow −

    x ** y;

    It returns the result of raising the first operand (x) to the power of the second operand (y).

    Example

    In the below code, we find the 22 using the exponentiation operator and store the resultant value in the 'res' variable.

    <html><body><div id ="output">The resultant value for2**2 is:</div><script>
    
      document.getElementById("output").innerHTML +=2**2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The resultant value for 2 ** 2 is: 4
    

    Exponentiation Assignment Operator

    The JavaScript exponentiation assignment operator raises the power of the first operand by the second operand and assigns it to the first operand.

    Syntax

    The syntax of exponentiation assignment operator is as follows −

    x **= y;

    It assigns the result of raising the first operand (x) to the power of the second operand (y) to x.

    Example

    In the below code, we find the 102 and assign the resultant value to the 'num' variable using the exponentiation assignment operator.

    <html><body><div id ="output">The resultant value for10**2 is:</div><script>let num =10;
    
      num **=2;// exponentiation assignment operation
      document.getElementById("output").innerHTML += num;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The resultant value for 10 ** 2 is: 100

  • ES5

    The ES6 version of JavaScript was released in 2015, marking the second major revision of JavaScript. The ES6 is also known as ECMAScript 2015. Some of the important features introduced in ES6 are arrow functions, let and const keywords, Classes, res parameters, etc. This chapter will discuss all the newly added features in ES6 version.

    New Added Features in ES6

    Here are the new methods, features, etc., added to the ES6 version of JavaScript.

    • Arrow Functions
    • Array find()
    • Array findIndex()
    • Array from()
    • Array keys()
    • Classes
    • const keyword
    • Default Parameters
    • For/of
    • Function Rest Parameter
    • JavaScript Modules
    • let keyword
    • Map Objects
    • New Global Methods
    • New Math Methods
    • New Number Methods
    • New Number Properties
    • Promises
    • Set Objects
    • String.endsWith()
    • String.includes()
    • String.startsWith()
    • Symbol
    • The spread Operator

    Here, we have explained each feature in detail with examples.

    JavaScript Arrow Functions

    The arrow function is a way to write the shorter function code. The concept of the arrow functions allows you to define the function without using the function keyword, curly braces, and return keyword.

    Example

    In the below code, func() is a regular function, and the variable subtracts stores the arrow function.

    <html><body><div id ="output">The subtraction of20 and 10 is:</div><script>/* Normal function
    
      function func(a, b) {
         return a - b;
      }
      */// Arrow functionconstsubtract=(a, b)=&gt; a - b;      
      document.getElementById("output").innerHTML +=subtract(20,10);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The subtraction of 20 and 10 is: 10
    

    JavaScript Array find() Method

    The JavaScript array.find() method returns the first element that follows the particular condition.

    Example

    In the below code, we find the first array element whose length is less than 4 using the array.find() method.

    <html><body><div id ="output">The first array element whose length is less than 4 is:</div><script>const strs =["Hello","World","How","are","You"];functionfunc_len(value, index, array){return value.length <4;}
    
        
      document.getElementById("output").innerHTML += strs.find(func_len);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The first array element whose length is less than 4 is: How
    

    JavaScript Array findIndex()

    The JavaScript array.findIndex() method is similar to the array.find() method, but it returns the index of the first element that matches the particular condition. It returns the 0-based index.

    Example

    In the below code, we find the index of the first element whose length is less than 4 using the array.findIndex() method.

    <html><body><div id ="output">The first array element whose length is less than 4 is:</div><script>const strs =["Hello","World","How","are","You"];functionfunc_len(value, index, array){return value.length <4;}
    
        
      document.getElementById("output").innerHTML += strs.findIndex(func_len);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The first array element whose length is less than 4 is: 2
    

    JavaScriipt Array from()

    The JavaScript Array.from() method creates an array from the iterable passed as an argument.

    Example

    In the below code, we create an array from the string using the Array.from() method. However, you can also pass iterable as an argument of the Array.from() method.

    <html><body><div id ="output">The array from the Hello string is:</div><script>
    
      document.getElementById("output").innerHTML += Array.from("Hello");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The array from the Hello string is: H,e,l,l,o
    

    JavaScript Array keys()

    The JavaScript array.keys() method returns an iterator to iterate the keys. The keys of the array element are indexes of the array elements.

    Example

    In the below code, we use the keys() method to get the iterators of keys of the nums[] array. After that, we use the for/of loop to traverse the keys of the array.

    <html><body><div id ="demo">The keys of the nums array is:<br></div><script>const output = document.getElementById("demo");const nums =[45,67,89,342,123,12];const iteratorNums = nums.keys();for(let key of iteratorNums){
    
         output.innerHTML += key +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The keys of the nums array is:
    0
    1
    2
    3
    4
    5
    

    JavaScript Classes

    Classes are essential in the object-oriented programming language. It is a blueprint for the object.

    You can use the class keyword to define the class. You can add constructors, properties, and methods to the class body. To access class properties and methods, you can use the class instance.

    Example

    In the below code, we have defined the animal class.

    The constructor initializes the value of the name and isVegetarian property. The getInfo() method returns the animal information.

    We created the object of the animal class and used it to invoke the getInfo() method of the class.

    <html><body><div id ="output">The animal information is:</div><script>classanimal{constructor(name, isVegetarian){this.name = name;this.isVegetarian = isVegetarian;}getInfo(){return"Name : "+this.name +", "+"isVegetarian? : "+this.isVegetarian;}}const lion =newanimal("Lion",false);
    
        
      document.getElementById("output").innerHTML += lion.getInfo();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The animal information is: Name : Lion, isVegetarian? : false
    

    JavaScript const keyword

    The JavaScript const keyword is used to declare the constant variables. You need to initialize the constant variables while declaring them.

    Example

    In the below code, the 'fruit' is a constant variable. You can't reinitialize its value.

    <html><body><div id ="output">The value of the fruit variable is:</div><script>const fruit ="Apple";// fruit = "Banana"; This is Invalid
    
      document.getElementById("output").innerHTML += fruit;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the fruit variable is: Apple
    

    JavaScript let keyword

    The JavaScript let keyword is used to define the blocked scope variables.

    Example

    In the below code, we have defined the variable 'a' using the let keyword inside the 'if' block. It can't be accessible outside the 'if' block due to its scoping behavior.

    <html><body><div id ="output"></div><script>if(true){let a =20;
    
         document.getElementById("output").innerHTML +="The value of a is: "+ a;}// You can't access it here.&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of a is: 20
    

    JavaScript Default Parameters

    The default parameters mean function parameters can have default values. When you don't pass enough arguments to the function, it uses the default parameter values.

    Example

    In the below code, the division () function takes two parameters. The default value of a is 10, and b is 2.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");functiondivision(a = 10, b = 2){return a / b;}
    
      output.innerHTML +="division(40, 5) =&gt; "+division(40,5)+"&lt;br&gt;";
      output.innerHTML +="division(40) =&gt; "+division(40)+"&lt;br&gt;";
      output.innerHTML +="division() =&gt; "+division();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    division(40, 5) => 8
    division(40) => 20
    division() => 5
    

    JavaScript forof Loop

    The JavaScript forof loop traverses the iterable like an array, string, set, map, etc.

    Example

    In the below code, we traverse the array of numbers and print each element of the array in the output.

    <html><body><div id ="output">The array elements are:</div><script>const array =[10,67,82,75,80];for(let number of array){
    
         document.getElementById("output").innerHTML += number +", ";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The array elements are: 10, 67, 82, 75, 80,
    

    JavaScript Function Rest Parameter

    When you are unsure about a number of the function argument, you can use the rest parameters. The rest parameter allows you to collect multiple arguments in a single array.

    Example

    We have passed the below code using the rest parameter with the sum() function. The name of the rest parameter can be a valid identifier, and it is used with the spread () operator.

    The sum() function adds the multiple numeric values and returns them.

    <html><body><div id ="output">sum(10,67,82,75,80)=</div><script>functionsum(...restParam){let res =0;for(let ele of restParam){
    
            res += ele;}return res;}
      document.getElementById("output").innerHTML +=sum(10,67,82,75,80);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sum(10, 67, 82, 75, 80) = 314
    

    JavaScript Modules

    In JavaScript, you can create different modules to write reusable code. After that, you can import the modules into the different JavaScript files.

    Default Export/Import modules

    const moduleMath ="This is the default value.";exportdefault moduleMath;// Exporting the module

    In other JavaScript files,

    // Importing the default moduleimport moduleMath from'./filename.js';
    console.log(moduleMath);

    Named Export/Import modules

    You can also export particular functions or properties from the modules and import them into other JavaScript files.

    // Exporting variablesexportconst size =90;// Exporting functionexportfunctionadd(a, b){return a + b;}

    In other JavaScript files,

    // Importing specific properties and functionsimport{ size, add}from'./filename.js';
    
    console.log(myVariable);// 90
    console.log(add(15,25));// 40

    JavaScript Map Objects

    The map is used to store the key-value pairs. You can use the Map() constructor to define a map.

    Example

    In the example below, we use the map to store the fruit's name and price. The set() method is used to insert the key-value pair into the fruit map, and the get() method is used to get the value of a particular key from the map.

    <html><body><div id ="output1">The price of the Apple is:</div><div id ="output2">The price of the Banana is:</div><script>const fruit =newMap();
    
      fruit.set("Apple",50);
      fruit.set("Banana",60);
      document.getElementById("output1").innerHTML += fruit.get("Apple")+"&lt;br&gt;";
      document.getElementById("output2").innerHTML += fruit.get("Banana");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The price of the Apple is: 50
    The price of the Banana is: 60
    

    New Global Methods

    In the ES6, below two global methods are added.

    • isFinite()
    • isNaN()

    isFinite()

    The isFinite() method checks whether the value passed as an argument is finite.

    Example

    In the below code, the num1 variable contains the infinity value, and num2 contains the valid numeric value.

    We used the isFinite() method to check whether the num1 and num2 variable's value is finite.

    <html><body><div id ="output"></div><script>const num1 =6453/0;const num2 =90;
    
      document.getElementById("output").innerHTML ="isFinite(6453 / 0): "+isFinite(num1)+"&lt;br&gt;"+"isFinite(90): "+isFinite(num2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    isFinite(6453 / 0): false
    isFinite(90): true
    

    isNaN()

    The isNaN() method checks whether the argument is a valid number. It returns false for the number value.

    Example

    In the below code, the isNaN() method returns true for the num1 variable, as it contains the string, and the string is not a number. For the num2 variable, the isNaN() method returns false, as it contains the numeric value.

    <html><body><div id ="output"></div><script>const num1 ="Hello";const num2 =867;
    
      document.getElementById("output").innerHTML ="isNaN(num1):  "+isNaN(num1)+"&lt;br&gt;"+"isNaN(num2):  "+isNaN(num2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    isNaN(num1): true
    isNaN(num2): false
    

    New JavaScript Math Methods

    In ES6, 5 new methods were added to the Math object.

    • Math.cbrt() − It is used to find the cube root of the given number.
    • Math.log2() It is used to find the logarithm of a number and uses the base 2.
    • Math.log10() It finds the base 10 logarithm of numeric value.
    • Math.trunc() It removes the decimal part from the floating point number and converts it into the whole number.
    • Math.sign() It returns 1, 0, and -1 based on the sign of the number passed as an argument.

    Example: Math.cbrt()

    The below code finds the cube root of the 64.

    <html><body><div id ="output">The cube root of the 64 is:</div><script>
    
      document.getElementById("output").innerHTML += Math.cbrt(64);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Math.log2()

    The below code finds the logarithm of 30 base 2.

    <html><body><div id ="output">The value of logarithm of30 base 2 is:</div><script>
    
      document.getElementById("output").innerHTML += Math.log2(30);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Math.log10()

    The below code finds the logarithm of 10 base 10.

    <html><body><div id ="output">The value of the logarithm of10 base 10 is:</div><script>
    
      document.getElementById("output").innerHTML += Math.log10(10);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Math.trunc()

    The below code truncates the floating point numbers using the Math.trunc() method.

    <html><body><div id ="output">After converting 23.2 to integer is:</div><script>
    
      document.getElementById("output").innerHTML += Math.trunc(23.2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Math.sign()

    <html><body><div id="output1">Math.sign(23):</div><div id="output2">Math.sign(-23):</div><script>
    
      document.getElementById("output1").innerHTML += Math.sign(23);
      document.getElementById("output2").innerHTML += Math.sign(-23);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    New Number Methods

    In ES6, two new number methods were added.

    • Number.isInteger() − It checks whether the number passed as an argument is a whole number or an integer.
    • Number.isSafeInteger() − It checks whether the number can be represented as a 64-bit double number.

    Example

    The below code checks whether 10 and 10.5 is an integer value. Also, it uses the isSafeInteger() method of the number class to check whether the number is safe integer.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");
    
      output.innerHTML +="Is 10 integer? "+ Number.isInteger(10)+"&lt;br&gt;";
      output.innerHTML +="Is 10.5 integer? "+ Number.isInteger(10.5)+"&lt;br&gt;";
        
      output.innerHTML +="Is 10000 safe integer? "+ Number.isSafeInteger(10000)+"&lt;br&gt;";
      output.innerHTML +="Is 10000000000000000000000 safe integer? "+ Number.isSafeInteger(10000000000000000000000);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Is 10 integer? true
    Is 10.5 integer? false
    Is 10000 safe integer? - true
    Is 10000000000000000000000 safe integer? - false
    

    New Number Properties

    In ES6, three new number properties were added.

    • EPSILON − It returns the value of the Epsilon.
    • MIN_SAFE_INTEGER − It returns the minimum integer value that a 64-bit number can represent.
    • MAX_SAFE_INTEGER − returns the maximum number, which can be represented by 64-bit.

    Example

    The below code shows the value of the Epsilon constant, minimum value of the safe integer, maximum value of the safe integer in JavaScript.

    <html><body><div id ="output1">The value of Epsilon is:</div><div id ="output2">The minimum safe integer is:</div><div id ="output3">The maximum safe integer is:</div><script>
    
      document.getElementById("output1").innerHTML +=  Number.EPSILON;
      document.getElementById("output2").innerHTML +=  Number.MIN_SAFE_INTEGER;
      document.getElementById("output3").innerHTML +=  Number.MAX_SAFE_INTEGER&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of Epsilon is: 2.220446049250313e-16
    The minimum safe integer is: -9007199254740991
    The maximum safe integer is: 9007199254740991
    

    JavaScript Promises

    In JavaScript, promises are used to handle the code asynchronously.

    It produces and consumes the code.

    Example

    In the below code, we used the Promise() constructor to create a promise. We resolve and reject the promise based on the random value generated using the random() method of the Math block.

    After that, we handle the promise using the then() and catch() block.

    <html><body><div id ="output"></div><script>// Creating a Promiseconst newPromise =newPromise((res, rej)=>{setTimeout(()=>{const rand_value = Math.random();if(rand_value <0.5){res("Value is less than 0.5");// Resolving the promise}else{rej("Value is greater than 0.5");// Rejecting the promise}},1000);// Adding 1 second delay});// Consuming the Promise
    
      newPromise
         .then((res)=&gt;{
             document.getElementById("output").innerHTML += res;}).catch((rej)=&gt;{
              document.getElementById("output").innerHTML += rej;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Value is greater than 0.5
    

    JavaScript Set Objects

    The Set() constructor is used to create a set. The set stores only unique elements of different types.

    Example

    In the below code, we created a new set and passed the array containing the number as an argument of the Set() constructor. The set contains only unique elements, which you can see in the output.

    <html><body><div id ="output">The set elements are:</div><script>const num_set =newSet([10,20,20,42,12]);for(let num of num_set){
    
         document.getElementById("output").innerHTML +=", "+ num;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The set elements are: , 10, 20, 42, 12
    

    JavaScript New String Methods

    In ES6, three new string methodswere added.

    • endsWith() − checks whether the string ends with a particular substring.
    • includes() − checks whether the string contains the substring at any position.
    • startsWith() − checks whether the string starts with a particular substring.

    Example

    The example below demonstrates how to use String endsWith(), includes(), and startsWith() methods with the help of an staing "How are you? I'm fine!".

    <html><body><div id ="output1">Does string end with'fine'?</div><div id ="output2">Does string include 'are'?</div><div id ="output3">Does string start with'How'?</div><script>let str ="How are you? I'm fine!";
    
      document.getElementById("output1").innerHTML +=  str.endsWith("fine!");
      document.getElementById("output2").innerHTML += str.includes("are");
      document.getElementById("output3").innerHTML += str.startsWith("How");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Does string end with 'fine'? true
    Does string include 'are'? true
    Does string start with 'How'? true
    

    JavaScript Symbol

    The JavaScript Symbol is a primate data type in JavaScript. In JavaScript, each Symbol is unique. You may use it to create unique ids.

    Example

    In the code below, we have defined two symbols and passed the same value as an argument. Still, both symbols are unique, which you can see in the output.

    <html><body><div id ="output"></div><script>const sym1 =Symbol("a");const sym2 =Symbol("a");if(sym1 == sym2){
    
         document.getElementById("output").innerHTML +="sym1 and sym2 are equal. &lt;br&gt;";}else{
         document.getElementById("output").innerHTML +="sym1 and sym2 are not equal.";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sym1 and sym2 are not equal.
    

    JabaScript Spread Operator

    The JavaScript spread operator allows you a create a copy of the iterable, like array, string, etc.

    Example

    The below code demonstrates using the spread operator to create an array of characters from the string.

    <html><body><div id ="output">The char array is:</div><script>let str ="Hello World!";const char =[...str];
    
      document.getElementById("output").innerHTML += char;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The char array is: H,e,l,l,o, ,W,o,r,l,d,!
  • ES5

    JavaScript ES5, also known as ECMAScript 5, was released in 2009. It was the first major revision of JavaScript. It introduced many new features, including getters and setters, and ‘use strict‘ directive. ES5 has provided significant improvement over the previous versions of JavaScript. The new features introduced in ES5 make code more powerful, concise and easier to maintain.

    New Added Features in JavaScript ES5

    Here are the new methods, features, etc., added to the ES5 version of JavaScript.

    • Array every()
    • Array filter()
    • Array forEach()
    • Array isArray()
    • Array indexOf()
    • Array lastIndexOf()
    • Array map()
    • Array reduce()
    • Array reduceRight()
    • Array some()
    • Date now()
    • Date toJSON()
    • Date toISOString()
    • Function bind()
    • JSON parse()
    • JSON stringify()
    • Multiline strings
    • Object methods
    • Object defineProperty()
    • Property getters and setters
    • Reserved words as property names
    • “use strict”
    • String[number] access
    • String trim()
    • Trailing commas

    Here, we have explained each feature in detail.

    JavaScript Array every()

    The array.every() method checks whether each element of the array follows a particular condition.

    Example

    In the below code, we use the array.every() method to check whether each element of the array is even.

    <html><body><div id ="output"> All elements of the array are even?</div><script>const arr =[10,20,30,40,2,6];functioneven(element){return element %2==0;}
    
      document.getElementById("output").innerHTML += arr.every(even);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    All elements of the array are even? true
    

    JavaScript Array filter()

    The array.filter() filters array elements and gets filtered elements in the new array.

    Example

    In the below code, we filter the array elements which are divisible by 10.

    <html><body><div id ="output"> Elements divisible by 10 are </div><script>const arr =[10,20,8,30,40,2,6];functiondivide(element){return element %10==0;}
    
      document.getElementById("output").innerHTML +=  arr.filter(divide);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Elements divisible by 10 are 10,20,30,40
    

    JavaScript Array forEach()

    The array.forEach() traverses the array elements. It is similar to loops in JavaScript.

    Example

    The below code uses the array.forEach() method to traverse the array and print each array element in the new line.

    <html><body><div id="output"></div><script>const arr =["TATA","Honda","Toyota","Maruti"];
    
      arr.forEach(traverse);// Using the array.forEach() methodfunctiontraverse(element){
         document.getElementById("output").innerHTML += element +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    TATA
    Honda
    Toyota
    Maruti
    

    JavaScript Array isArray()

    The Array.isArray() method checks whether the object passed as an argument is an array.

    Example

    The below code checks whether the arr is an array using the Array.isArray() method.

    <html><body><div id ="output"></div><script>const arr =["TATA","Honda","Toyota","Maruti"];let bool = Array.isArray(arr);
    
      document.getElementById("output").innerHTML +="Is arr array? "+ bool;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Is arr array? true
    

    JavaScript Array indexOf()

    The array.indexOf() method returns the first index of the particular element in the array.

    Example

    The below code finds the first index of 23 in the array, which is 0.

    <html><body><div id ="output"> The first index of23in the array is </div><script>const arr =[23,45,32,12,23,56];
    
      document.getElementById("output").innerHTML += arr.indexOf(23);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The first index of 23 in the array is 0
    

    JavaScript Array lastIndexOf()

    The array.lastIndexOf() method returns the last index of the particular element in the array.

    Example

    The code below finds the last index of the 45 in the array, which is 4.

    <html><body><div id ="output"> The last index of45in the array is </div><script>const arr =[23,45,32,45,45,56];
    
      document.getElementById("output").innerHTML += arr.lastIndexOf(45);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The last index of 45 in the array is 4
    

    JavaScript Array map()

    The array.map() method returns a new array after mapping current array elements with new ones.

    Example

    The below code uses the map() method to create a new array by doubling the array elements.

    <html><body><div id ="output"> The newarray is </div><script>const arr =[1,2,3,4,5];functiondoubleEle(element){return element *2;}
    
      document.getElementById("output").innerHTML += arr.map(doubleEle);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The new array is 2,4,6,8,10
    

    JavaScript Array reduce()

    The array.reduce() method reduces the array to a single value.

    Example

    The below code multiples all elements of the array using the array.reduce() method.

    <html><body><div id ="output">The multiplication result of the array elements is </div><script>const arr =[1,2,3,4,5];functionmultiplier(multiplication, element){return multiplication *2;}
    
      document.getElementById("output").innerHTML += arr.reduce(multiplier);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The multiplication result of the array elements is 16
    

    JavaScript Array reduceRight()

    The array.reduceRight() method reduces the array from right to left instead of left to right.

    Example

    <html><body><div id ="output">The merged array elements in the reverse order is:</div><script>const arr =["How","are","you","doing?"];functionmerge(res, element){return res += element +" ";}
    
      document.getElementById("output").innerHTML += arr.reduceRight(merge);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The merged array elements in the reverse order is: doing?you are How
    

    JavaScript Array some()

    The array.some() method is used to check whether some elements of the array follow the particular condition.

    Example

    The code below checks whether the array contains 1 or more strings with lengths greater than 3.

    <html><body><div id ="output">Array contains one or more strings with lengths greater than 3?</div><script>const arr =["How","are","you","doing?"];functionfunc_len(element){return element.length >3;}
    
      document.getElementById("output").innerHTML += arr.some(func_len);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Array contains one or more strings with lengths greater than 3? true
    

    JavaScript Date now()

    The Date.now() method is used to get the total number of milliseconds since 1st January 1970.

    Example

    The below code finds the total milliseconds from 1st January 1970.

    <html><body><div id ="output">Total milliseconds since 1st January,1970 is:</div><script>
    
      document.getElementById("output").innerHTML += Date.now();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Total milliseconds since 1st January, 1970 is: 1702540225136
    

    JavaScript Date toJSON()

    The date.toJSON() method converts the date into the JSON date format. The JSON date format is the same as the ISO format. The ISO format is YYYY-MM-DDTHH:mm:ss.sssZ.

    Example

    The below code prints the current date in JSON format.

    <html><body><div id ="output">The current date inJSON format is:</div><script>const date =newDate();
    
      document.getElementById("output").innerHTML += date.toJSON();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The current date in JSON format is: 2023-12-18T06:12:52.366Z
    

    JavaScript Date toISOString()

    The date.toISOString() method is used to convert the date into the ISO standard format.

    Example

    The below code prints the current date in the standard ISO string format.

    <html><body><div id ="output">The current date inISO string format is:</div><script>const date =newDate();
    
      document.getElementById("output").innerHTML += date.toISOString();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The current date in ISO string format is: 2023-12-18T06:13:50.159Z
    

    JavaScript Function bind()

    The bind() method is used to borrow the method from another object.

    Example

    In the below code, the bird object contains the properties and printInfo() method. The animal object contains only name and category properties.

    We used the bind() method to borrow the printInfo() method from the bird object for the animal object. In the output, the printInfo() method prints the information of the animal object.

    <html><body><div id ="result"></div><script>const output = document.getElementById("result");const bird ={
    
         name:"Parrot",
         category:"Bird",printInfo(){return"The name of the "+this.category +" is - "+this.name;}}const animal ={
         name:"Lion",
         category:"Animal",}const animalInfo = bird.printInfo.bind(animal);
      output.innerHTML +=animalInfo();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The name of the Animal is - Lion
    

    JavaScript JSON parse()

    The JSON.parse() method is used to convert the string into the JSON object.

    Example

    The code given below converts the string into an object. Also, we have printed the values of object properties in the output.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");const objStr ='{"name":"Sam", "age":40, "city":"Delhi"}';const obj =JSON.parse(objStr);
    
      output.innerHTML +="The parsed JSON object values are - &lt;br&gt;";
      output.innerHTML +="name : "+ obj.name +"&lt;br&gt;";
      output.innerHTML +="age : "+ obj.age +"&lt;br&gt;";
      output.innerHTML +="city: "+ obj.city +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The parsed JSON object values are -
    name : Sam
    age : 40
    city: Delhi
    

    JavaScript JSON stringify()

    The JSON.stringify() method converts the object into a string.

    Example

    The code below converts the obj object into the string using JSON.strringify() method.

    <html><body><div id ="output">The object in the string format is -</div><script>const obj ={
    
         message:"Hello World!",
         messageType:"Welcome!",}
      document.getElementById("output").innerHTML +=JSON.stringify(obj);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The object in the string format is - {"message":"Hello World!","messageType":"Welcome!"}
    

    JavaScript Multiline Strings

    You can use the backslash (\) to break the line of the string and define the string in multiline.

    Example

    In the below example, we have defined the str string in multiple lines and used the backslash to break the line.

    <html><body><div id ="output"></div><script>let str ="Hi \
    
                 user";
      document.getElementById("output").innerHTML +="The string is - "+ str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The string is - Hi user
    

    JavaScript Object Methods

    In ES5, object-related methods are added to manipulate and protect the objects.

    Methods to Manipulate the Object

    Sr.No.MethodDescription
    1create()To creat a new object, using an existing object as the prototype.
    2defineProperty()To make a clone of the object and add new properties to its prototype.
    3defineProperties()To define a property into a particular object and get the updated object.
    4getOwnPropertyDescriptor()To get the property descriptor for the properties of the object.
    5getOwnPropertyNames()To get object properties.
    6getPrototypeOf()To get the prototype of the object.
    7keys()To get all keys of the object in the array format.

    Methods to Protect the Object

    Sr.No.MethodDescription
    1freeze()To prevent adding or updating object properties by freezing the object.
    2seal()To seal the object.
    3isFrozen()To check if the object is frozen.
    4isSealed()To check if the object is sealed.
    5isExtensible()To check if an object is extensible.
    6keys()To get all keys of the object in the array format.
    7preventExtensions()To prevent the prototype updation of the object.

    JavaScript Object defineProperty()

    You can use the Object.definedProperty() method to define a single property of the object or update the property value and metadata.

    Example

    The code below contains the car object's brand, model, and price properties. We used the defineProperty() method to define the gears property in the object.

    <html><body><div id ="output">The obj object is -</div><script>const car ={
    
         brand:"Tata",
         model:"Nexon",
         price:1000000,}
      Object.defineProperty(car,"gears",{
         value:6,
         writable:true,
         enumerable:true,
         configurable:true})
        
      document.getElementById("output").innerHTML +=JSON.stringify(car);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The obj object is - {"brand":"Tata","model":"Nexon","price":1000000,"gears":6}
    

    JavaScript Property getters and setters

    The getters and setters are used to access and update the object properties securely.

    Example

    In the below code, the watch object contains the brand and dial properties. We have defined the getter using the get keyword to access the brand property value.

    Also, we have defined the setter using the set keyword to set the dial property value in the upper case.

    In this way, you can secure the updating object property value.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");const watch ={
    
         brand:"Titan",
         dial:"ROUND",// Getter to get brand propertygetwatchBrand(){returnthis.brand;},// Setter to set Watch dialsetwatchDial(dial){this.dial = dial.toUpperCase();}}
      output.innerHTML ="The Watch brand is - "+ watch.watchBrand +"&lt;br&gt;";
      watch.watchDial ="square";
      output.innerHTML +="The Watch dial is - "+ watch.dial;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The Watch brand is - Titan
    The Watch dial is - SQUARE
    

    JavaScript Reserved words as property names

    After ES5, you can use the reversed words as a property name in the object.

    Example

    In the below code, delete is used as an object property name.

    <html><body><div id ="output">The obj object is -</div><script>const obj ={
    
         name:"Babo",delete:"Yes",}
      document.getElementById("output").innerHTML +=JSON.stringify(obj);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The obj object is - {"name":"Babo","delete":"Yes"}
    

    JavaScript "use strict"

    The strict mode was also introduced in the ES5.

    The strict mode allows you to overcome errors and write clear code. You can use the use strict directive to declare the strict mode.

    Example

    In the below code, you can uncomment the num = 43 line and observe the error. The strict mode doesnt allow developers to define the variables without using var, let, or const keywords.

    <html><body><div id ="output">The value of num is:</div><script>"use strict";let num =43;// This is valid// num = 43; // This is invalid
    
      document.getElementById("output").innerHTML += num +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of num is: 43
    

    JavaScript String[number] access

    Before ES5, the charAt() method was used to access the string character from a particular index.

    After ES5, you can consider the string as an array of characters and access string characters from the specific index as you access array elements.

    Example

    <html><body><div id ="output1">The first character in the string is:</div><div id ="output2">The third character in the string is:</div><script>let str ="Apple";
    
      document.getElementById("output1").innerHTML += str[0];
      document.getElementById("output2").innerHTML += str[2];&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The first character in the string is: A
    The third character in the string is: p
    

    JavaScript String trim()

    The string.trim() method removes the whitespaces from both ends.

    Example

    In the below code, we used the string.trim() method to remove the whitespaces from the start and end of the str string.

    <html><body><div id ="output"></div><script>let str ="    Hi, I am a string.    ";
    
      document.getElementById("output").innerHTML = str.trim();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hi, I am a string.
    

    JavaScript Trailing commas

    You can add a trailing comma (A comma after the last element) in the array and object.

    Example

    In the below code, we have added the trailing comma after the last object property and array element. The code runs without error and prints the output.

    <html><body><div id ="demo1"></div><div id ="demo2"></div><script>const obj ={
    
         name:"Pinku",
         profession:"Student",}
      document.getElementById("demo1").innerHTML =JSON.stringify(obj);let strs =["Hello","world!",];
      document.getElementById("demo2").innerHTML = strs;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    {"name":"John","profession":"Student"}
    Hello,world!
    

    Note The JSON string doesnt allow the trailing comma.

    For example,

    let numbers ='{"num1": 10,"num2": 20,}';JSON.parse(numbers);// Invalid
    
    numbers ='{"num1": 10,"num2": 20}';JSON.parse(numbers);// Valid

    In ES5, mostly array and object-related methods are introduced.

  • Versions

    JavaScript was developed by Brendan Eich in 1995. It was standardized in 1997 by European Computer Manufacturers Association (ECMA) and officially known as ECMAScript. The first version of the language is known as ECMSScript 1 (abbreviated as ES1). The fist three versiosn (ES1, ES2, and ES3) laid the foundation of the language. The fourth version, ES4, was abandoned. The first main revision done in ES5(2009). The second major revised version is ES6 (ECMAScript 2015). After 2015, the versions are named by the year in which it it released.

    The latest version of JavaScript is ECMAScript 2023.

    JavaScript Versions

    In the Below table, we have specified detailed information about each version.

    VersionOfficial NameRelease YearFeatures Added
    ES1ECMAScript 11997First release
    ES2ECMAScript 21998Minor changes
    ES3ECMAScript 31999Added regular expressionsAdded do-whileAdded switchAdded try/catch
    ES4ECMAScript 4Never Released.
    ES5ECMAScript 52009JavaScript strict modeMultiline stringsString.trim()Array methodsObject methodsGetters and settersTrailing commas
    ES6ECMAScript 20152015let and const statementsMap and set objectsArrow functionsFor/of loopSome array methodsSymbolClassesPromisesJavaScript ModulesNew Number methods and propertiesFor/of loopSpread operator
    ES7ECMAScript 20162016Exponential (**) operatorArray.includes() method
    ES8ECMAScript 20172017Added Async/awaitAdded Object.entries() methodAdded Object.values() methodAdded Object.getOwnPropertyDescriptor() methodAdded string padding
    ES9ECMAScript 20182018Rest object propertiesJavaScript shared memoryPromise.finally() methodNew features of the RegExp() object
    ES10ECMAScript 20192019String trim.start()String trim.end()Array.flat()Revised Array.sort()Revised JSON.stringify() / toString()Object.fromEntries() method
    ES11ECMAScript 20202020Nullish Coalescing Operator (??)BigInt primitive data type
    ES12ECMAScript 20212021String.replaceAll() methodPromise.Any() method
    ES13ECMAScript 20222022The static block inside the classNew class featuresTop-level await
    ES14ECMAScript 20232023Array findLast() & findLastIndex()Hashbang GrammerSymbols as WeakMap keys

    Since 2016, early update is being released with version named by the year of release. The update release in June 2023 is known as ECMAScript 2023.

  • History

    JavaScript has changed the website, application, and game development world and revolutionized the digital industry. JavaScript is mainly used with HTML and CSS to develop the application interface. However, nowadays, it is also used as a server-side programming language. In the world, according to stackoverflow survey 2023, around 63% of developers are using JavaScript.

    History of JavaScript

    Let’s discuss a brief history of JavaScript.

    First stage development of JavaScript

    In 1993, Some developers released the web browser Mosaic, with a graphical interface. In 1994, Netscape was founded by the lead developers of the Mosaic web browser. They have also released the browser named Netscape Navigator.

    Till 1996, websites were static, containing only HTML and CSS. So, dynamic behavior needed to be added to the web page to make the website more interactive. The scripting language is required to add the dynamic behavior to the web page.

    Netscape’s lead software developer, Brendan Eich, developed the scripting language in September 1995 within 10 days. ‘Mocha’ name was given to the newly developed scripting language and renamed later to ‘LiveScript’ and then ‘JavaScript’.

    The name JavaScript is given from the ‘Java’ language. Java was the most popular language in those days, and the script was added due to the scripting language.

    Standardization of JavaScript

    JavaScript was only supported by the Internet Explorer browser when it was developed. However, the internet explorer browser is deprecated now.

    In 1997, to promote JavaScript across all web browsers, Netscape submitted a proposal to the European Computer Manufacturers Association (ECMA) for standardizing JavaScript.

    This is how ECMAScript(ES) came into the world of development. After that, the JavaScript developer’s community and Netscape update the JavaScript continuously, adding new features to the JavaScript and releasing the new version, ES1, ES2, , ES13, etc.

    The latest version of JavaScript is ES13.

    JavaScript Libraries and Frameworks

    After 2005, a revolution came into JavaScript development.

    In 2006, one of the most popular libraries, JQuery, was developed to make website development more accessible. However, JavaScript supports thousands of libraries nowadays.

    In 2010, frameworks like Ember, Backbone, etc., were introduced. The framework provides the structure of the application. In 2013, one of the most popular frameworks named, React, was introduced.

    Server-side JavaScript

    In 2009, the NodeJS runtime environment was introduced by Ryan Dhal to create server-side applications. Due to NodeJS, developers can use JavaScript for full-stack web development, and JavaScirpt is not limited to front-end development.

    Currently, Google is managing NodeJS.

    Modern JavaScript and ES6 Release

    In 2015, the ES6 version of JavaScript was released. In the Es6 version, JavaScript developers have significantly changed JavaScript and added more advanced features.

    The latest version of JavaScript Es13 was released in 2022.

    History table of JavaScript

    YearECMAscript VersionFeature Released
    1995Brendan Eich has developed JavaScript.
    1996JavaScript 1.0 was released.
    1997ES1Standardization of JavaScript occurred by ECMA, and the ES1 version was released.
    1998ES2ES2 version of JavaScript released.
    1999ES3ES3 version of JavaScript released.
    2006The first library, JQuery developed to use JavaScript.
    2008ES4ES4 version of JavaScript released.
    2009NodeJS was developed for the server-side programming language.
    2009ES5ES5 version of JavaScript released.
    2010The first framework, Angular JS, was developed.
    2013The most popular JavaScript framework, ReactJS developed.
    2015ES6ES6 version of JavaScript released.
    2016ES7ES7 version of JavaScript released.
    2017ES8ES8 version of JavaScript released.
    2018ES9ES9 version of JavaScript released.
    2019ES10ES10 version of JavaScript released.
    2020ES11ES11 version of JavaScript released.
    2021ES12ES12 version of JavaScript released.
    2022ES13ES13 version of JavaScript released.

    Future of JavaScript

    In the world, 98% of websites use JavaScript as a client-side programming language.

    The increasing demand for websites, applications, software, etc., also increases the demand for JavaScript. As time passes, the developer’s community develops more libraries and frameworks supported by JavaScript, making it easier to develop the digital product.

    There are 14+ million JavaScript developers in the world, and the number is growing. Overall, the future of JavaScript is bright.

  • Proxies

    Proxy in JavaScript

    The JavaScript proxies are objects that allow you to wrap a particular object and customize the fundamental operations of the object, like getting and setting object properties. In short, using the proxy object, you can add custom behavior to the object. The proxies are used to implement features such as logging, caching, and securities.

    We can create a proxy object using the Proxy() constructor in JavaScript. The constructor accepts two parameters target object and handler object. It returns a new proxy object for the target object.

    Syntax

    Following is the syntax to create a proxy object in JavaScript −

    const obj =newProxy(targetObj, Handler);

    We used the Proxy() constructor with a new keyword in the above syntax.

    Parameters

    The Proxy constructor takes two parameters.

    • targetObj − It is a target object for which you want to create a proxy object and customize its default behavior.
    • Handler − It is an object containing the functionality to customize the behavior of the target object.

    Example

    In the example below, the person object contains the name and age property.

    We have defined the proxy object for the person object named proxyObj. Also, we passed the handler object as a Proxy() constructor parameter.

    In the handler object, we have defined the getters to access the object property. The getters check whether the object contains the property you are looking for. If yes, it returns the property value. Otherwise, it returns the message saying the object doesn’t contain the property.

    <html><body><div id ="demo1">The name of the person is:</div><div id ="demo2">The height of the person is:</div><script>const person ={
    
         name:"Same",
         age:32,}const handler ={// Defining the gettersget:function(object, property){return object[property]? object[property]:'Object doesnt contain the property.';}}const proxyObj =newProxy(person, handler);
      document.getElementById("demo1").innerHTML += proxyObj.name;
      document.getElementById("demo2").innerHTML += proxyObj.height;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The name of the person is: Same
    The height of the person is: Object doesnt contain the property.
    

    When you access the non-existing property from the object, it returns the undefined. Here, we have customized the object's default behavior to return a nice and readable method.

    If you pass the empty handler object while creating the proxy object, the proxy object will work the same as the original object.

    JavaScript Proxy Handlers

    There are multiple proxy handlers available in JavaScript, and we have covered some of them below. The proxy handlers are used to override the default behavior of the object.

    The JavaScript get() proxy handler

    The get() proxy handler in JavaScript allows you to change the property accessing behavior of the object.

    Syntax

    Follow the syntax below to use the get() proxy handler with the proxy object.

    get(target, property, receiver)

    Parameters

    • target − It is a target object.
    • property − It is a property whose value is needed to access.
    • receiver − It is a proxy object itself.

    Example

    In the below code, the watch object contains the brand, color, and price property. We have created the proxy for the watch object.

    The handler object contains the get() handler and returns the property value if it is not. Otherwise, it returns a readable message.

    <html><body><div id ="output1">Brand:</div><div id ="output2">Price:</div><script>const watch ={
    
         brand:"Casio",
         color:"Blue",
         price:null,}const handler ={get(object, property){return object[property]!=null? object[property]:"Property is null.";}}const wathcProxy =newProxy(watch, handler);
      document.getElementById("output1").innerHTML += wathcProxy.brand;
      document.getElementById("output2").innerHTML += wathcProxy.price;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Brand: Casio
    Price: Property is null.
    

    The JavaScript set() proxy handler

    The set() proxy handler in JavaScript is used to change the default behavior of updating the property of the object.

    Syntax

    Follow the syntax below to use the set() proxy handler.

    set(target, property, value, receiver)

    Parameters

    • target − It is a target object.
    • property − It is a property to change its value.
    • value − It is an updated value.
    • receiver − It is a proxy object itself.

    Example

    In the below code, the handler object contains the set() proxy handler. The set() handler checks whether the property is equal to the 'price. If yes, it updates the property value with a new value. Otherwise, it sets 'Not Available' to the object property.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");const watch ={
    
         brand:"Casio",
         color:"Blue",
         price:null,}const handler ={set(object, property, value){if(property ==="price"){
               object[property]= value;}else{
               object[property]="Not Available";}}}const wathcProxy =newProxy(watch, handler);
      wathcProxy.price =2000;
      wathcProxy.dial ="Round";
      output.innerHTML +="Price: "+ wathcProxy.price +"&lt;br&gt;";
      output.innerHTML +="Dial: "+ wathcProxy.dial +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Price: 2000
    Dial: Not Available
    

    The JavaScript apply() proxy handler

    The apply() proxy handler is used to change the default behavior of the function call.

    Syntax

    Follow the syntax below to use the apply() proxy handler.

    apply(target, thisArg, arguments)

    Parameters

    • target − It is a target function needed to execute.
    • thisArg − It refers to the context whose elements should be accessed using this keyword in the function body.
    • arguments − It is an array of arguments to pass to the function.

    Example

    In the below code, getDetails is a proxy object created for the getWatchDetails() function. The handler object contains the apply() method and calls the target function.

    We have called the getDetails() proxy by passing the watch object as a parameter.

    <html><body><p id ="output"></p><script>const watch ={
    
         brand:"Casio",
         color:"Blue",
         price:2000,}constgetWatchDetails=function(watch){return`Brand: ${watch.brand},  
         Color: ${watch.color}, 
         price: ${watch.price}`;}const getDetails =newProxy(getWatchDetails,{apply(target, thisArg, args){returntarget(...args).toUpperCase();}});
      document.getElementById("output").innerHTML +=getDetails(watch);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    BRAND: CASIO, COLOR: BLUE, PRICE: 2000
    

    Uses of the Proxy Object in JavaScript

    Here, we have explained the benefits of using the proxy object with examples.

    For Validation

    You can use the proxy object in JavaScript to validate the property values while updating the value of the property or adding a new property to the object.

    Example

    In the below code, the numbers object contains the num1, num2, and num3 properties. The set() proxy handler checks whether the new value is greater than the current value. If yes, it updates the value. Otherwise, it keeps old values.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");const numbers ={
    
         num1:10,
         num2:20,
         num3:30,}const handler ={set(object, property, value){if(value &gt; object[property]){// Validing the new value using the previous value
               object[property]= value;}}}const numberProxy =newProxy(numbers, handler);
      numberProxy.num1 =20;
      numberProxy.num2 =10;
      output.innerHTML +="num1: "+ numbers.num1 +", num2: "+ numbers.num2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1: 20, num2: 20
    

    For Access Control

    You can also use the proxy handler to control the access of the object in JavaScript. For example, you can restrict users from updating the object properties and making them read-only.

    Example

    In the below code, whenever you try to update the object property value, it prints the message that the object is read-only.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");const numbers ={
    
         num1:10,
         num2:20,
         num3:30,}const handler ={set(object, property, value){
            output.innerHTML +="Object is read-only.&lt;br&gt;"}}const numberProxy =newProxy(numbers, handler);
      numberProxy.num1 =20;
      output.innerHTML +="num1: "+ numberProxy.num1;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Object is read-only.
    num1: 10
    

    Side Effects

    You may call the functions or class methods when anyone tries to access or update the object property.

    Example

    In the example below, the emailValidator() function checks whether the email includes the '@'. If yes, it returns true. Otherwise, it returns false.

    In the set() proxy handler, we update the property value based on the returned value of the emailValidator() function.

    <html><body><p id ="output"></p><script>const emails ={
    
         email1:"[email protected]",}// Function to validate the emailfunctionemailValidator(email){if(email.includes("@")){returntrue;}else{returnfalse;}}const handler ={set(object, property, value){if(emailValidator(value)){
               object[property]= value;}}}const emailProxy =newProxy(emails, handler);
      emailProxy.email1 ="[email protected]";
      document.getElementById("output").innerHTML ="email1: "+ emailProxy.email1;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    email1: [email protected]
    

    However, usage of the proxy handers is not limited, and we can't cover each use case in this tutorial. So, you may explore more use cases of the proxy handlers.

    JavaScript Proxy Handlers List

    Here, we have listed all proxy handlers in JavaScript.

    Proxy Handler Methods

    Sr.No.Proxy HandlerDescription
    1apply()It changes the default behavior of the function call.
    2construct()Trapping the construction of new object.
    3defineProperty()Changing the behavior of defining new property.
    4deleteProperty()Changing the behavior of deleting the new property.
    5get()Changing the behavior of accessing object property.
    6getOwnPropertyDescriptor()To trap the getOwnPropertyDescriptor() method of the object.
    7getPrototypeOf()Trapping the internal methods.
    8has()To manipulate the checking of whether an object contains the property.
    9isExtensible()To trap the isExtensible() method of the Object.
    10ownKeys()To change the behavior of the ownKeys() method.
    11preventExtension()To trap the preventing extension of the object.
    12set()To change the default behavior of adding new property or updating a property value of the object.
    13setPrototypeOf()To customize the Object.setPrototypeOf() method.

    Constructor

    Sr.No.ConstructorDescription
    1Proxy()It is used to create a proxy object.

    Static Method

    Sr.No.MethodDescription
    1revocable()It is also used to create a new proxy object similar to the Proxy() constructor.
  • Mixins

    Mixins in JavaScript

    The mixins in JavaScript allow you to add the properties of the other objects or classes to the target object’s or class’s prototype and extend the functionality of the target object. After that, you can access the other object’s method using the target object.

    In JavaScript, each object contains a built-in property called prototype. The prototype is itself an object. So prototype object will have its own prototype property making what we call prototype changing. Prototype chain helps to inherit properties and methods from other objects.

    Also, you can say that mixins allow you to borrow functionality from other objects or classes.

    In JavaScript, inheritance allows you to extend the functionality of the object or class. Similarly, Mixins also allows you to extend the functionality of the object or classes.

    JavaScript Mixins with Objects

    Using the concept of the JavaScript mixins, you can extend the functionality of the target object by adding properties and methods of the other objects.

    Syntax

    Following is the syntax to use Mixins with objects in JavaScript −

    Object.assign(target, obj);

    In the above syntax, we used the Object.assign() method to extend the functionality of the target object.

    Parameters

    • target − It is an object whose functionality you need to extend.
    • obj − It is an object whose functionality will be extended by the target object.

    Example

    In the below code, the parent object contains the printMessage(), and the child object contains the showName() method. Both methods print different messages.

    After that, we used the Object.assign() method to extend the functionality of the child object with the methods of the parent object.

    Next, we invoke the parent and child object message using the child object only, and you can observe the output.

    <html><body><p id ="output"></p><script>const output = document.getElementById("output");const parent ={
    
         name:"parent",printMessage(){
            output.innerHTML ='This is a parent object.&lt;br&gt;';}}const child ={showName(){
            output.innerHTML +='This is a child object.&lt;br&gt;';}}
      Object.assign(child, parent);// Mixins
      child.printMessage();//Executing the method of parent object using child object
      child.showName();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    This is a parent object.
    This is a child object.
    

    JavaScript Mixins with Classes

    You can also extend the functionality of the classes through objects using the mixins.

    Syntax

    We can follow the syntax below to use mixins with classes −

    Object.assign(class_name.prototype, obj);

    In the above syntax, we have passed the prototype of the class as the first parameter and the object as a second parameter whose functionalities need to extend with classes.

    Example

    In the below code, the animal object contains the 'eats' property and run() method. The cat class contains only the constructor.

    We add the methods and properties of the animal object to the cat class's prototype. After that, we execute the run() method using the instance of the cat class.

    <html><body><p id ="output"></p><script>const output = document.getElementById("output");const animal ={
    
         eats:true,run(){
            output.innerHTML +="Animals run. &lt;br&gt;";}}classcat{constructor(){this.name ="Cat";}}
      Object.assign(cat.prototype, animal);// Mixinsconst catObj =newcat();
      output.innerHTML +="Cat eats: "+ catObj.eats +"&lt;br&gt;";
      catObj.run();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Cat eats: true
    Animals run.
    

    Achieving Multiple Inheritance Using the Mixins

    JavaScript doesn't support multiple inheritance, which means extending one class's functionality with multiple classes or objects. So, you can achieve multiple inheritance using mixins.

    Syntax

    Users can follow the syntax below to use the mixins to achieve multiple inheritance.

    Object.assign(target, ob1, obj);

    The above syntax will add the obj1 and obj2 object's functionality to the target object.

    Example: Inheriting multiple objects

    In the below code, eat object contains the eatFood() method, and the drink object contains the drinkWater() method.

    We add properties and methods of the eat and drink object to the person object. After that, we access the eatFood() and drinkWater() methods using the person object.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");const eat ={eatFood(){
    
            output.innerHTML +="Person is eating the food! &lt;br&gt;";}}const drink ={drinkWater(){
            output.innerHTML +="Person is drinking water! &lt;br&gt;";}}const person ={
         name:"John",}
      Object.assign(person, eat, drink);// Mutiple Mixins
      person.eatFood();
      person.drinkWater();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Person is eating the food!
    Person is drinking water!
    

    Example: Multiple Inheritance with Classes

    The below example demonstrates extending one class with multiple classes.

    The Entity class is the parent class, and it contains the state() method. The Human class extends the Entity class and contains the walk() method.

    The Driver() function creates a new class, extends a class passed as a parameter, and adds the Drive() method to the class. Similarly, the Swimmer() function creates a new class, extends the class with a class passed as a parameter, and adds the swim() method.

    After that, we defined multiple other classes. The person class extends the class returned by the Driver() class. The Driver() function returns a new class extended with the Human class. Same way, we have created the Mechanic and SwimmerPerson classes.

    After that, we have created the objects of various classes and executed the methods inherited by them.

    <html><body><p id ="demo"></p><script>let output = document.getElementById("demo");// Parent classclassEntity{state(){return'It is in the idle state!';}}// Child classclassHumanextendsEntity{walk(){return'walking on the field.';}}// Custom functionalitiesfunctionDriver(parentClass){returnclassextends parentClass {drive(){return'driving on the road';}};}functionSwimmer(parentClass){returnclassextends parentClass {swim(){return'swimming in water';}};}// Some other classesclassPersonextendsDriver(Human){}classMechanicextendsDriver(Entity){}classSwimmerPersonextendsSwimmer(Person){}// Objects of classesconst person =newPerson();const personDrive = person.drive();const mechanic =newMechanic();const mechanicDrive = mechanic.drive();const swimmerPerson =newSwimmerPerson();const swimmerDrive = swimmerPerson.drive();const swimmerSwim = swimmerPerson.swim();// Printing outputs
    
      output.innerHTML +='State of the PERSON: '+ personDrive +'&lt;br&gt;';
      output.innerHTML +='State of the MECHANIC: '+ mechanicDrive +'&lt;br&gt;';
      output.innerHTML +='State of the SWIMMER PERSON: '+ swimmerDrive +", "+ swimmerSwim +'&lt;br&gt;';&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    State of the PERSON: driving on the road
    State of the MECHANIC: driving on the road
    State of the SWIMMER PERSON: driving on the road, swimming in water
    

    This way, you can use the mixins to achieve multiple inheritance.

    Benefits of using Mixins

    Here, we have listed some benefits of using mixins.

    • Code reusability − You can reuse the code by borrowing methods and properties from other objects of other classes.
    • Multiple inheritance − JavaScript doesn't support multiple inheritance by default, but you can achieve similar functionalities using mixins.
    • Extensibility − You can add additional functionalities to the classes or objects without changing the structure of the objects or classes using mixins.

    Limitations of Mixins

    Here, we have listed some limitations of mixins and reasons why some developers avoid using mixins.

    • Complexity − If you overuse the mixins, it increases the complexity of the code, which you can see in the last example of this tutorial.
    • Pseudo inheritance − The mixin can fulfill the requirements of the inheritance, but using the mixins, you can't achieve true inheritance.
    • Naming collision − If you combine multiple objects, there is a high chance of naming collision.
  • Global Object

    Global Objects in JavaScript

    The JavaScript global object allows you to access the variables, functions, objects, etc., defined in the global scope and available everywhere in the code.

    In the browser, a global object is named as ‘window‘, and in Node.js, the global object is named ‘global‘. However, the global object could have different names in different run-time environments.

    The ‘globalThis‘ has been introduced in ECMAScript 2020, which works with most browsers and run time environments as a global object.

    Syntax

    We can follow the syntax below to use the global object to access the variables available everywhere in the JavaScript code.

    var a =10;let b = window.a;// Accessing the global variable in the browser

    In the above syntax, variable ‘a’ is a global variable, as it is defined in the global scope using the var keyword.

    Examples

    Example: Accessing global variables through the global object

    In the below example, we have defined the ‘name’ variable in the global scope using the var keyword. After that, we access the name variable using the window (global) object.

    <html><body><div id ="output">The company name is:</div><script>var name ="Tutorialspoint";let company = window.name;
    
      document.getElementById("output").innerHTML += company;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The company name is: Tutorialspoint
    

    Similarly, if you define the function in the global scope, you can access it anywhere using the global object.

    Example: Accessing the global function through the global object

    In the below example, we have defined the sum() function in the global scope. After that, we have defined the obj object containing the num1, num2, and sum properties. The sum properties are initialized with a value returned by the sum() function. We used the' window' object to invoke a global sum() function.

    So, you can access the global variable and instances anywhere in the JavaScript code using the global object.

    <html><body><p id ="output"></p><script>functionsum(a, b){return a + b;}const obj ={
    
         num1:10,
         num2:20,
         sum: window.sum(10,20),}
        
      document.getElementById("output").innerHTML +="The object is: "+JSON.stringify(obj);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The object is: {"num1":10,"num2":20,"sum":30}
    

    If you want to make value globally accessible from the local scope, you can directly add value to the 'window' object as a property.

    Let's look at the example below.

    Example: Making variable globally accessible from the function scope

    In the example below, we add the 'addition' property to the window object in the sum() function's body to make it available everywhere.

    After that, we access the 'addition' property using the 'window' object.

    <html><body><div id ="output"></div><script>functionsum(a, b){
    
         window.addition = a + b;}sum(20,30);
      document.getElementById("output").innerHTML ="The sum is: "+ window.addition;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The sum is: 50
    

    You can also access the global variables without using the global object like a window, as the script is assigned under the object by the JavaScript scripting engine by default. However, you can use the global object to make a variable or expression global.

    The JavaScript global object itself contains various methods like isNaN(), decodeURI(), etc. You can access them using the global object-like window in the browser and global in Node.js.

    Example: Accessing pre-defined methods of the global object

    The JavaScript isNaN() method of the window object is used to check whether the argument passed is a number or not. If the argument is a number, it returns false. Otherwise, it returns true.

    <html><body><p id ="output"></p><script>let isNumer = window.isNaN("Hello");
    
      document.getElementById("output").innerHTML ="Is hello not a number? "+ isNumer;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Is hello not a number? true
    

    Using the JavaScript Global Object for Polyfills

    You can use the JavaScript global object to check whether your browser supports a particular feature. You can show a related message if the user's browser does not support a particular feature.

    Look at the example below to check whether the user's browser supports the promises.

    Example

    In the below code, we check whether the 'promise' property exists in the window object. If yes, promises are supported by the browser, and you can execute the promise. Otherwise, you can print the message that your browser doesn't support promise.

    <html><body><p id ="output"></p><script>const output = document.getElementById("output");if(window.Promise){
    
         output.innerHTML +="Your browser supports promises";}else{
         output.innerHTML +="Your browser doesn't support promises";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Your browser supports promises
    

    The JavaScript global object only stores the truly global variables. You shouldn't store the variable in the global object that is not global. Otherwise, it can create conflicts in your project.

  • Optional Chaining

    The optional chaining in JavaScript allows you to access nested properties and methods of an object without checking if each property exists. This can help to make your code more concise and easier to read.

    The optional chaining operator (?.) is sued to achieve optional chaining in JavaScript. It is placed before the property or method that you want to access. If the property or method does not exist, the expression will evaluate to undefined instead of throwing an error.

    The Non-existing Property Problem

    Let’s understand the need for optional chaining in JavaScript via the non-existing property problem.

    While working with objects in JavaScript, you may have objects with dynamic properties. Some properties also contain the object as a value, called nested objects.

    JavaScript can throw an error if you try to access the nested property whose parent doesn’t exist.

    For example,

    const parent ={
    
    child:{
        name:"Smith",}}const name = parent.child.name;</pre>

    The parent object contains the 'ch' property, and the 'ch' property contains the nested object as a value.

    In the code, you access the 'name' property of the 'child' nested object, but the 'child' property doesn't exist in the parent object. So, JavaScript will throw the below error as you access the undefined property.

    Uncaught TypeError: Cannot read properties of undefined
    

    To solve the above problem, the '&&' operator was used before ES11.

    For example,

    if(parent.child && parent.child.name){// access parent.child.name here}

    In the above code, we first check whether the parent.child exists. If yes, we access its name property to avoid the error.

    You got the solution, but what if you need to access the property from the 4th or 5th level of the object? You need to use multiple && operators and write complex code.

    Here, the optional chaining operator (?.) comes into the picture to solve the non-existing property problem easily.

    What is an Optional Chaining in JavaScript?

    In JavaScript, optional chining operator (?.) is introduced in ECMAScript 2020 (ES2020). It provides the best way to access object properties, array elements, etc.

    The optional chaining is very similar to normal chaining used to access the nested properties of the object. It checks whether the nested property exists before accessing the object property to avoid the error.

    Syntax

    You can follow the syntax below to use the optional chaining operator in JavaScript.

    Obj?.prop1?.nestedprop;// Accessing nested properties
    Obj?.[expression];// Accessing object property via expression
    Array?.[index];// Accessing array element
    funcName?.();// Executing the funciton 
    • In the above syntax, if the obj object exists, it will access the prop1 property. Again the code checks if the prop1 property exists in the obj object, it will access the nestedProp property. Otherwise, it will stop the code execution to avoid errors.
    • You can also access the object property value using the expression and optional chaining.
    • Optional chaining can also be used for accessing array elements and executing the function.

    Return value

    If a property does not exist, the optional chain returns undefined without throwing any error.

    Example

    In the example below, the car object contains the 'info' nested object. The info object contains the color and price property.

    We try to access the price property of the info object using the optional chain, it returns 5000000.

    After that, we try to access the gears property of the engine property of the car object using the optional chain. In the output, you can see that it returns undefined rather than throwing an error.

    <html><body><div id ="output1">The price of the Audi Q6 is:</div><div id ="output2">Total gears in the Audi Q6 is:</div><script>const car ={
    
         brand:"Audi",
         model:"Q6",
         info:{
            price:5000000,
            color:"Black",}}
      document.getElementById("output1").innerHTML += car.info?.price;
      document.getElementById("output2").innerHTML += car.engine?.gears;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The price of the Audi Q6 is: 5000000
    Total gears in the Audi Q6 is: undefined
    

    Optional Chaining with Function Calls

    In JavaScript, you can also use the optional chaining with the function calls. If the function is not defined, it will return the undefined. Otherwise, the code will execute the function.

    Example

    In the below code, we used the optional chain with object methods.

    The car object contains the getBrand() method. We used the optional chain while executing the getBrand() method, which returns 'Audi'.

    Also, we try to execute the getColor() method of the car object with an optional chain. It returns undefined as the car object doesn't contain the getColor() method.

    <html><body><div id ="output1">The brand of the car is:</div><div id ="output2">The color of the car is:</div><script>const car ={getBrand(){return"Audi";},}
    
      document.getElementById("output1").innerHTML += car.getBrand?.();
      document.getElementById("output2").innerHTML += car.getColor?.();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The brand of the car is: Audi
    The color of the car is: undefined
    

    Optional Chaining with Expression

    You can use the optional chain while accessing the object properties using the expression or array element.

    Example

    In the below code, the animal object contains the name and info property. The info property again contains the nested object having legs and tail properties.

    We access the object properties using the optional chain and expression. You can see that it prints the output in the code without throwing any error, even the 'specs' property doesn't exist in the animal object.

    <html><body><div id ="output1">Total number of legs of the tiger is:</div><div id ="output2">The color of the tiger is:</div><script>const animal ={
    
         name:"Tiger",
         info:{
            legs:4,
            tail:1,}}
      document.getElementById("output1").innerHTML += animal.info?.["legs"];
      document.getElementById("output2").innerHTML += animal.specs?.["color"];&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Total number of legs of the tiger is: 4
    The color of the tiger is: undefined
    

    Optional Chaining with the "delete" Operator

    The JavaScript delete operator is used to delete the object properties. If you try to delete properties that do not exist, the code will throw an error. So, you can use the optional chain operator with the delete operator.

    Example

    In the below code, we delete the legs property of the nested info object and the tail property of the 'specs' nested object using the delete operator and access properties using the optional chain.

    The animal object doesn't contain the specs property. Still, the code runs without any error due to the optional chain.

    <html><body><div id ="demo"></div><script>const animal ={
    
         name:"Tiger",
         info:{
            legs:4,
            tail:1,}}delete animal.info?.legs;delete animal.sepcs?.tail;
      document.getElementById("demo").innerHTML ="Updated object is: "+JSON.stringify(animal);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Updated object is: {"name":"Tiger","info":{"tail":1}}
    

    Short-circuiting with Optional Chaining

    In JavaScript, the meaning of short-circuiting is that whenever you get an error, stop the execution of the code. You can use the optional chain for accessing each nested property of the object to avoid any error and stop the execution of the code on error.

    Example

    In the below code, the animal object contains the info object, and the info object contains the legs object. We use the optional chain to access each nested property. So, if any property doesn't exist, it will return undefined and avoid errors.

    <html><body><div id ="output1">The size of the first leg is:</div><div id ="output2"> The size of the third leg is:</div><script>const animal ={
    
         name:"Tiger",
         info:{
            legs:{
               first:1.32,
               second:1.31,},
            tail:1,}}
      document.getElementById("output1").innerHTML += animal?.info?.legs?.first;
      document.getElementById("output2").innerHTML += animal?.specs?.legs?.third;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The size of the first leg is: 1.32
    The size of the third leg is: undefined
    

    Nullish Coalescing Operator with Optional Chaining

    When any object property doesn't exist, the optional chain stops the code execution and returns undefined. If you use the JavaScript nullish coalescing operator with it, you can return the default value when the object property doesn't exist.

    Example

    In the below code, we try to access the color property of the 'specs' object of the 'animal' object. Here, 'specs' do not exist in the animal object. So, it returns 'red' as we used the nullish coalescing operator.

    <html><body><div id ="output">The color of the animal is:</div><script>const animal ={
    
         name:"Tiger",
         info:{
            legs:2,
            tail:1,}}
      animal.info?.legs;const color = animal?.spec?.color ??"Red";
      document.getElementById("output").innerHTML += color;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The color of the animal is: Red
    

    In simple terms, you can use the optional chain operator wherever you need to access the properties of the dynamic object to avoid an error.

  • Nested Destructuring

    Nested Destructuring

    The Nested Destructuring in JavaScript allows us to extract data from nested objects and arrays. An object (or array) can contain another object (or array) inside itself, known as a nested object (or array). Unpacking the nested objects or arrays is called nested destructuring. We can extract all or some data from the objects or arrays using destructuring.

    We can assign the extracted data from nested array or object to the variables. This is referred as nested destructuring assignment. When using nested destructuring to get some values from a nested array or object, you have to follow the structure of the array or object.

    Nested Object Destructuring

    This section will demonstrate nested object destructuring in JavaScript.

    Syntax

    The syntax of nested object destruction in JavaScript is as follows −

    const{prop1, prop2:{nestedprop1, nestedprop2}}= obj;

    In the above syntax, prop1 is a property of the object, and the prop2 property contains the nested object, having nestedprop1 and nestedprop2 properties.

    Example

    In the example below, the car object contains the brand, model, and info properties. The info property contains the nested object containing the price and color properties.

    We have destructured the nested object and printed the values of the variables in the output.

    <html><body><p id ="output"></p><script>const car ={
    
         brand:"Hyundai",
         model:"Verna",
         info:{
            price:1200000,// Nested properties
            color:"white",}}const{ brand, model, info:{ price, color }}= car;// Destructuring
      document.getElementById("output").innerHTML =Brand: ${brand} &amp;lt;br&amp;gt; Model: ${model} &amp;lt;br&amp;gt; Price: ${price} &amp;lt;br&amp;gt; Color: ${color};&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Brand: Hyundai
    Model: Verna
    Price: 1200000
    Color: white
    

    Example: Nested object destructuring and renaming variables

    The below code demonstrates that you can rename the variables while unpacking the nested object properties.

    We have renamed the brand, model, price, and color variables to company, name, cost, and carColor.

    <html><body><p id ="output"></p><script>const car ={
    
      brand:"Hyundai",
      model:"Verna",
      info:{
         price:1200000,// Nested properties
         color:"white",}}// Destructuringconst{brand: company, model: name, info:{price: cost, color: carColor }}= car;
    document.getElementById("output").innerHTML =Company: ${company}, Name: ${name}, Cost: ${cost}, Color: ${carColor};</script></body></html>

    Output

    Company: Hyundai, Name: Verna, Cost: 1200000, Color: white
    

    Example: Nested object destructuring and default values

    You can use the assignment operator to assign the default values to the variables. Whenever particular property of the object is undefined, it initializes the variable with the default value.

    Here, we have renamed each variable and assigned default values. The 'science' property is not defined in the grades (nested object) object. So, the code prints its default value in the output.

    <html><body><p id ="output"></p><script>const student ={
    
         firstName:"Sam",
         lastName:"Raina",
         grades:{
            English:75,}};const{ firstName: name ="Jay", 
         lastName: surname ="Shah", 
         grades:{ English: eng =0, Science: sci =0}}= student;
      
      document.getElementById("output").innerHTML =Name: ${name} &amp;lt;br&amp;gt; Surname: ${surname} &amp;lt;br&amp;gt; English: ${eng} &amp;lt;br&amp;gt; Science: ${sci};&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Name: Sam
    Surname: Raina
    English: 75
    Science: 0
    

    Example: Nested object destructuring and rest operator

    The rest operator allows you to collect the remaining properties into a single object.

    In the below code, the grades object contains 4 different properties. We have stored the value of the Maths property in the Maths variables and other properties in the 'allGrades' variable using the rest operator. The 'allGrades' is an object containing 3 properties.

    <html><body><p id ="output"></p><script>const student ={
    
         firstName:"Kunal",
         lastName:"Karma",
         grades:{
            English:75,
            Maths:87,
            SocialScience:90,
            Science:80,}};const{ firstName, lastName, grades:{ Maths,...allGrades }}= student;
      document.getElementById("output").innerHTML =`firstName: ${firstName} &lt;br&gt;
    lastName: ${lastName} <br> Maths: ${Maths} <br> allGrades: ${JSON.stringify(allGrades)} <br> `;</script></body></html>

    Output

    firstName: Kunal
    lastName: Karma
    Maths: 87
    allGrades: {"English":75,"SocialScience":90,"Science":80}
    

    Nested Array Destructuring

    This section will demonstrate nested array destructuring in JavaScript.

    Syntax

    The syntax to unpack nested array elements (nested array destructuring) in JavaScript is as follows −

    const[a,[b, c], d]= arr;

    In the above syntax, we store the nested array elements in the b and c variables.

    Example

    In the below code, the arr array contains the nested array. We unpack the nested array elements into the variables b and c. In the output, you can observe the values of the b and c variables.

    <html><body><p id ="output"></p><script>const arr =[10,[15,20],30];const[a,[b, c], d]= arr;
    
      document.getElementById("output").innerHTML ="a = "+ a +", b = "+ b +", c = "+ c +", d = "+ d;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a = 10, b = 15, c = 20, d = 30
    

    Example: Skipping elements of the nested array

    Assignment destructuring allows you to skip the elements of the nested array. Here, the arr array contains two nested arrays. We skip the first element of each nested array while destructuring the nested array.

    <html><body><p id ="output"></p><script>const arr =[2,[3,4],[9,10]];const[a,[, b],[, c]]= arr;
    
      document.getElementById("output").innerHTML ="a = "+ a +", b = "+ b +", c = "+ c;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a = 2, b = 4, c = 10
    

    Example: Nested array destructuring and default values

    You can assign default values to the variables like objects while destructuring the nested arrays.

    Here, the first nested array of arr [3, 4] contains two elements. While destructuring, we skipped the first two elements and used the variable p to get the third element, but the nested array contains only two elements. So, the value of the variable p is a 29 default value.

    <html><body><p id ="output"></p><script>const arr =[2,[3,4],[9,10]];const[,[,, p =29],[, q]]= arr;
    
      document.getElementById("output").innerHTML ="p = "+ p +", q = "+ q;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    p = 29, q = 10
    

    Example: Nested array destructuring and rest operator

    You can use the rest operator with nested array destructuring. Here, variable b stores the remaining elements of the first nested array, and variable c stores the remaining elements of the parent array, which includes the second nested array and last array element.

    <html><body><p id ="output"></p><script>const arr =[[6,7,8,9],[10,11,12,13],14];const[[a,...b],...c]= arr
    
      document.getElementById("output").innerHTML ="a = "+ a +"&lt;br&gt; b = "+ b +"&lt;br&gt; c = "+ c;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a = 6
    b = 7,8,9
    c = 10,11,12,13,14
    

    Array Within Object Nested Destructuring

    Sometimes, we need to destructure the object containing the array. Let's understand it via the example below.

    Example

    In the example below, the num2 property of the numbers object contains the array. We destructure the object properties and print the values in the output.

    <html><body><p id ="output"></p><script>const numbers ={
    
         num1:10,
         num2:[40,6,5],}const{num1, num2:[a, b, c]}= numbers;
      document.getElementById("output").innerHTML ="num1 = "+ num1 +", a = "+ a +", b = "+ b +", c = "+ c;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1 = 10, a = 40, b = 6, c = 5
    

    Object Within Array Nested Destructuring

    In some cases, an array can also contain the object, and you need to destructure the object from the array.

    Example

    In the below code, the numbers array contains the object containing the p and q properties.

    After that, we destructure the array and unpack the object properties.

    <html><body><p id ="output"></p><script>const numbers =[10,{ p:20, q:30}]const[a,{ p, q }]= numbers;
    
      document.getElementById("output").innerHTML ="a = "+ a +", p = "+ p +", q = "+ q;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a = 10, p = 20, q = 30