Blog

  • 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

  • Array Destructuring

    Array Destructuring

    JavaScript Array destructuring allows us to unpack the values from array and assign them to the variables. After that, you can use the variables to access their value and use them in the code. We can perform the array structuring using the destructuring assignment. The destructuring assignment is a basically a JavaScript expression.

    Syntax

    The syntax of array destructuring assignment in JavaScript is as follows

    const array =[10,20];const[var1, var2]= array;

    In the above syntax, the “array” is the original array containing 10 and 20. When you unpack the array elements, var1 contains the 10, and var2 contains the 20.

    Example: Basic Array Destructuring

    In the example below, the arr array contains 3 numeric values. After that, we used the array destructuring to unpack array elements and store them in the num1, num2, and num3 variables.

    <html><body><div id ="output1"></div><div id ="output2"></div><div id ="output3"></div><script>const arr =[100,500,1000];const[num1, num2, num3]= arr;
    
    
      document.getElementById("output1").innerHTML ="num1: "+ num1;
      document.getElementById("output2").innerHTML ="num2: "+ num2;
      document.getElementById("output3").innerHTML ="num3: "+ num3;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1: 100
    num2: 500
    num3: 1000
    

    Example: Unpacking with initial N elements of the array

    While destructuring the array, if the left operand has fewer variables than array elements, first, N array elements get stored in the variables.

    The array contains 6 elements in the below code, but 2 variables exist on the left side. So, the first 2 elements of the array will be stored in the variables, and others will be ignored.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>const arr =[1,2,3,4,5,6];const[num1, num2]= arr;
    
       
      document.getElementById("output1").innerHTML ="num1: "+ num1;
      document.getElementById("output2").innerHTML ="num2: "+ num2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1: 1
    num2: 2
    

    Skipping Array Elements While Destructuring an Array

    While JavaScript array destructuring, you can skip a particular array element without assigning it to a variable.

    Example

    In the below code, the arr array contains 6 numbers. We have skipped the 2nd and 4th elements. In the output, num3 is 3, and num5 is 5, as the 2nd and 4th elements are skipped.

    <html><body><div id ="output"></div><script>const arr =[1,2,3,4,5,6];const[num1,, num3,, num5]= arr;
    
      document.getElementById("output").innerHTML ="num1: "+ num1 +"&lt;br&gt;"+"num3: "+ num3 +"&lt;br&gt;"+"num5: "+ num5;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1: 1
    num3: 3
    num5: 5
    

    Array Destructuring and Rest Operator

    If the left operand of the destructuring assignment operator contains fewer variables than the array elements, JavaScript ignores the last remaining array elements.

    To solve the problem, you can use the rest operator. You can write the last variable with a rest operator in the left operand. So, the remaining array elements will be stored in the operand of the rest operator in the array format.

    Example

    In the code below, the array's first and second elements are stored in the num1 and num2 variables. We used the rest operator with the num3 variable. So, the remaining array elements will be stored in num3 in the array format.

    <html><body><div id ="demo"></div><script>const arr =[1,2,3,4,5,6];const[num1, num2,...nums]= arr;
    
      document.getElementById("demo").innerHTML ="num1: "+ num1 +"&lt;br&gt;"+"num2: "+ num2 +"&lt;br&gt;"+"nums: "+ nums;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1: 1
    num2: 2
    nums: 3,4,5,6
    

    If you use the rest operator in the middle, all remaining array elements will be stored in the operand of the rest operator, and variables used after the rest operator will be ignored.

    Array Destructuring and Default Values

    Sometimes, an array can contain undefined values or fewer elements than the variables. In such cases, while destructuring JavaScript arrays, the variables can be initialized with the default values.

    Example

    In the below code, num1, num2, and num3 contain 10, 20, and 30 default values, respectively. The array contains only a single element.

    So, when we unpack the array, the num1 variable will contain the array element, num2 and num3 will contain the default values.

    <html><body><div id ="demo"></div><script>const arr =[1];const[num1 =10, num2 =20, num3 =30]= arr;
    
      document.getElementById("demo").innerHTML ="num1: "+ num1 +"&lt;br&gt;"+"num2:  "+ num2 +"&lt;br&gt;"+"num3: "+ num3;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1: 1
    num2: 20
    num3: 30
    

    Swapping Variables Using Array Destructuring

    You can also swap two variables values using the JavaScript Array Destructuring.

    Example

    In the below code, variables a and b are initialized with 50 and 100, respectively. After that, we added variables a and b in a different order in the left and right operands. In the output, you can see the swapped values of the a and b.

    <html><body><div id ="output"></div><script>let a =50, b =100;
    
      document.getElementById("output").innerHTML ="Before Swapping: a = "+ a +", b = "+ b +"&lt;br&gt;";[b, a]=[a, b]
      document.getElementById("output").innerHTML +="After Swapping: a = "+ a +", b = "+ b;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Before Swapping: a = 50, b = 100
    After Swapping: a = 100, b = 50
    

    Destructuring the Returned Array from the Function

    In real-time development, dynamic arrays are returned from the function. So, you can also destructure the returned array from the function.

    Example

    In the example below, getNums() function returns the array of numbers.

    We execute the getNums() function and unpack array elements in the individual variables.

    <html><body><div id ="output"></div><script>functiongetNums(){return[99,80,70];}const[num1, num2, num3]=getNums();
    
      document.getElementById("output").innerHTML ="num1: "+ num1 +"&lt;br&gt;"+"num2: "+ num2 +"&lt;br&gt;"+"num3: "+ num3;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1: 99
    num2: 80
    num3: 70

  • Object Destructuring

    Object Destructuring

    The object destructuring assignments are JavaScript expressions that allow you to unpack and assign object properties into individual variables. The name of the individual variables can be the same as the object properties or different.

    The object destructuring is a very useful feature when you have an object with a lot of properties and you only need a few of them.

    Syntax

    The syntax of Object Destructing assignment in JavaScript is as follows

    const{ prop1, popr2 }= obj;ORconst{ prop1: p1, prop12: p2 }= obj;// Renaming variablesORconst{ prop1 = default_vaule }= obj;// With Default valuesORconst{ prop1,...prop2 }= obj;// With rest parameter

    In the above syntax, ‘obj’ is an object. The prop1 and prop2 are object properties. It covers the different use cases of object destructuring.

    Example: Basic Object Destructuring

    In the example below, the watch object contains the brand and price properties.

    We store the values of the object properties into the individual variables using object destructuring. You can see the brand’s value and price variable in the output, which is the same as object property values.

    <html><body><p id ="output"></p><script>const watch ={
    
         brand:"Titan",
         price:6000,}const{brand, price}= watch;
      document.getElementById("output").innerHTML +="The brand of the watch is "+ brand +" and the price is "+ price;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The brand of the watch is Titan and the price is 6000
    

    Example: Destructuring with less properties

    The code below demonstrates that you can unpack only required object properties and keep others as it is. Here, the Object contains total 4 properties. But we have unpacked only brand and price properties.

    <html><body><p id ="output"></p><script>const watch ={
    
         brand:"Titan",
         price:6000,
         color:"Pink",
         dial:"Round",}const{ brand, price }= watch;
      document.getElementById("output").innerHTML ="The brand of the watch is "+ brand +" and the price is "+ price;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The brand of the watch is Titan and the price is 6000
    

    Object Destructuring and Renaming Variables

    In JavaScript object destructuring, it is not necessary to store the object property values in the variables with the same name as object properties.

    You can write a new variable name followed by a colon followed by an object property name. In this way, you can rename the object properties while destructuring the object.

    Example

    In the example below, we have stored the value of the brand property in the 'bd' variable, the color property in the 'cr' variable, and the dial property in the 'dl' variable.

    The values of the new variables are the same as the object properties.

    <html><body><p id ="output1">brand:</p><p id ="output2">color:</p><p id ="output3">dial:</p><script>const watch ={
    
         brand:"Titan",
         color:"Pink",
         dial:"Round",}const{ brand: bd, color: cr, dial: dl }= watch;
       
      document.getElementById("output1").innerHTML += bd;
      document.getElementById("output2").innerHTML += cr;
      document.getElementById("output3").innerHTML += dl;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    brand: Titan
    
    color: Pink
    
    dial: Round
    

    Object Destructuring and Default Values

    In many situations, an object property may contain an undefined value, or particular property doesn't exist in the object. If the property is undefined, JavaScript destructuring assignment allows you to initialize the variables with default values.

    Example

    In the below code, the animal object contains the name and age properties.

    We destructure the object and try to get the name and color property values from the object. Here, the color property doesn't exist in the object, but we have initialized it with the default value.

    The output shows 'yellow' as the color variable's value, which is the default value.

    <html><body><p id ="output1">Animal Name:</p><p id ="output2">Animal Color:</p><script>const animal ={
    
         name:"Lion",
         age:10,}const{ name ="Tiger", color ="Yellow"}= animal;
      document.getElementById("output1").innerHTML += name;
      document.getElementById("output2").innerHTML += color;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Animal Name: Lion
    
    Animal Color: Yellow
    

    Example

    In the below code, we have renamed the variables and assigned the default values to the variables. We used the colon to change the variable name and the assignment operator to assign the default values.

    <html><body><p id ="output1">Animal Name:</p><p id ="output2">Animal Color:</p><script>const animal ={
    
         name:"Lion",
         age:10,}const{ name: animalName ="Tiger", color: animalColor ="Yellow"}= animal;
      document.getElementById("output1").innerHTML += animalName;
      document.getElementById("output2").innerHTML += animalColor;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Animal Name: Lion
    
    Animal Color: Yellow
    

    Object Destructuring and Rest Operator

    The syntax of the JavaScript Rest parameter is three dots (...). It allows you to collect the remaining object properties into a single variable in the object format. Let's understand it via the example below.

    Example

    In the below code, the nums object contains the 4 properties. While destructuring, the object value of the num1 property is stored in the num1 variable. Other remaining properties are stored in the 'numbers' variable using the rest operator.

    In the output, you can see that 'numbers' contains the object containing the remaining properties of the nums object.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");const nums ={
    
         num1:10,
         num2:20,
         num3:30,
         num4:40,}const{num1,...numbers}= nums;
      output.innerHTML +="num1: "+ num1 +"&lt;br&gt;";
      output.innerHTML +="numbers: "+JSON.stringify(numbers);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1: 10
    numbers: {"num2":20,"num3":30,"num4":40}
    

    Object Destructuring and Function Parameter

    You can pass the JavaScript object as a function argument. After that, you can destructure the object in the parameter of the function definition.

    Example

    In the below code, the nums object contains multiple properties, and we have passed it as an argument of the sum() function.

    In the function parameter, we destructure the object and use that variable inside the function body. The function body returns the sum of object properties.

    <html><body><p id ="output"></p><script>functionsum({ num1, num2, num3, num4 }){return num1 + num2 + num3 + num4;}const nums ={
    
         num1:5,
         num2:7,
         num3:10,
         num4:12,}const res =sum(nums);
      document.getElementById("output").innerHTML +="The sum of numbers is: "+ res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The sum of numbers is: 34

  • Destructuring Assignment

    Destructuring Assignment

    In JavaScript, the destructuring assignment is an expression that allows us to unpack the values from the arrays or objects and store them in individual variables. It is a technique to assign array values or object properties to the variables.

    The destructuring assignment syntax is introduced in ECMAScript 6 (ES6). Before ES6, developers were unpacking the object properties manually as shown in the example below.

    Array unpacking before ES6

    In the example below, the ‘arr’ array contains the fruit names. After that, we created different variables and assigned array elements to the variables.

    <html><body><p id ="output"></p><script>const arr =["Apple","Banana","Watermelon"];const fruit1 = arr[0];const fruit2 = arr[1];const fruit3 = arr[2];
    
    
      document.getElementById("output").innerHTML ="fruit1: "+ fruit1 +"&lt;br&gt;"+"fruit2: "+ fruit2 +"&lt;br&gt;"+"fruit3: "+ fruit3;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    fruit1: Apple
    fruit2: Banana
    fruit3: Watermelon
    

    The above code will work if the array doesn't contain the dynamic number of elements. What if the array contains 20+ elements? Will you write 20 lines of the code?

    Here the concept of the destructuring assignment comes into the picture.

    Array Destructuring Assignment

    You can follow the syntax below to use destructuring assignment to unpack array elements.

    const[var1, var2, var3]= arr;

    In the above syntax, 'arr' is an array. The var1, var2, and var3 are variables to store array elements. You can also similarly unpack the objects.

    Example

    The below example implements the same logic as the above example. Here, we have used the destructuring assignment to unpack the array elements. The code gives the same output as the previous example.

    <html><body><p id ="output"></p><script>const arr =["Apple","Banana","Watermelon"];const[fruit1, fruit2, fruit3]= arr;
    
    
      document.getElementById("output").innerHTML ="fruit1: "+ fruit1 +"&lt;br&gt;"+"fruit2: "+ fruit2 +"&lt;br&gt;"+"fruit3: "+ fruit3;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    fruit1: Apple
    fruit2: Banana
    fruit3: Watermelon
    

    Example: Nested Array Destructuring

    In the example below, we created a nested array. To access these elements, we used nested array destructuring assignment. Try the following example

    <html><body><p id ="output"></p><script>const arr =["Apple",["Banana","Watermelon"]];const[x,[y, z]]= arr;
    
      document.getElementById("output").innerHTML = 
      x +"&lt;br&gt;"+
      y +"&lt;br&gt;"+
      z ;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Apple
    Banana
    Watermelon
    

    Object Destructuring Assignment

    You can follow the syntax below to use destructuring assignment to unpack object elements.

    const{prop1, prop2, prop3}= obj;

    In the above syntax, 'obj' is an object. The prop1, prop2, and prop3 are variables to store object properties.

    Example

    The below example implements the same logic as in the example of array destructuring assignment. Here, we have used the destructuring assignment to unpack the object elements.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>const fruit ={
    
         name:"Apple",
         price:100,}const{name, price}= fruit;
      document.getElementById("output1").innerHTML ="fruit name: "+ name;
      document.getElementById("output2").innerHTML ="fruit price: "+ price;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    fruit name: Apple
    fruit price: 100
    

    Example: Nested Object Destructuring

    In the example below, we defined a nested object called person with two properties age and name. The name property contains two properties called fName and lName. We access these properties using nested destructuring.

    <html><body><div id ="output"></div><script>const person ={
    
         age:26,
         name:{
            fName:"John",
            lName:"Doe"}}// nested destructuring const{age, name:{fName, lName}}= person;
      document.getElementById("output").innerHTML ="Person name: "+ fName +" "+ lName +"&lt;br&gt;"+"Person age: "+ age;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Person name: John Doe
    Person age: 26
    

    What's Next?

    In the next chapters, we will learn the below concepts in detainls.

    • Array destructuring − Unpacking the array elements.
    • Object destructuring − Unpacking the object properties.
    • Nested destructuring − Unpacking the nested array elements and nested objects.
  • Destructuring

    Destructuring is a simple term we can use to extract values from array and properties from object. It is a JavaScript expression that help to unpack values from array or similarly properties from object into different variables.

    Let’s say you have a box that contain multiple items. Now, imagine someone asks you to take out a particular item from the box, then you will need to check each item one by one and this increases complexity right? Then we just simplify it by using destructuring and get the exact item at once.

    When to use Destructuring?

    We use destructuring in the following scenarios −

    • When we need more than one property from object or more than one value from the array, we can use destructuring for that.
    • Suppose, there is a situation where we need to assign more than one value to variables, we can use destructuring to achieve it.
    • If we need to pass an object as a function parameter, we can use destructuring to extract the properties of the object.
    • If there is a need to return multiple values from a function, we can use destructuring to return them as an object.
    • It is easy to use destructuring when working with arrays and objects.

    Types of Destructuring

    There are two types of destructuring in JavaScript those are shown below −

    • Object Destructuring: It is used to extract properties from an object.
    • Array Destructuring: It is used to extract elements from an array.

    Object Destructuring

    Object destructuring means when we extract some properties from an object and assign them to variables. It allow us to write short code and also it helps us to improve our code readability.

    Array Destructuring

    Array destructuring is Same as object destructuring, We can also destructure an array, extract elements from an array and assign them to variables.

  • Polymorphism

    Polymorphism in JavaScript

    The polymorphism in JavaScript allows you to define multiple methods with the same name and different functionalities. Polymorphism is achieved by using method overloading and overriding. JavaScript does not support method overloading natively. Method overriding allows a subclass or child class to redefine a method of superclass or parent class. In this chapter, we will implement the polymorphism using the concept of method overriding.

    The polymorphism word is derived from the geek word polymorph. If you break the polymorph, the meaning of the ‘poly’ means many, and ‘morph’ means transforming from one state to another state.

    Method Overriding

    Before you understand the polymorphism, it is important to understand the method overriding.

    If you define a method with the same name in the parent and child class, the child class method overrides the parent class’s method.

    For example, you want to calculate the area of the different shapes. You have defined the Shape class containing the area() method. Now, you have a different class for the different shapes, and all extend the Shape class, but you can’t use the area() method of the Shape class to find the area of each shape as each geometry has a different formula to find the area.

    So, you need to define the area() method in each child class, override the area() method of the Shape class, and find the area of the particular shape. This way, you can create many forms of the single method.

    Examples

    Let’s understand the polymorphism and method overriding via the example below.

    Example 1: Demonstrating Polymorphism in JavaScript

    In the example below, the Shape class contains the area() method. The Circle and Rectangle, both classes, extend the Shape class. Also, the area() method is defined in the Circle and Rectangle class.

    There are 3 area() methods defined in the below code, but which method will invoke it depends on which class’s instance you are using to invoke the method.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>classShape{area(a, b){return"The area of each Geometry is different! <br>";}}classCircleextendsShape{area(r){// Overriding the method of the Shape classreturn"The area of Circle is "+(3.14* r * r)+"<br>";}}classRectangleextendsShape{area(l, b){// Overriding the method of the Shape classreturn"The area of Rectangle is "+(l * b)+"<br>";}}const circle =newCircle();// Calling area() method of Circle class
    
      document.getElementById("output1").innerHTML = circle.area(5);const rectangle =newRectangle();// Calling area() method of Rectangle class
      document.getElementById("output2").innerHTML = rectangle.area(5,10);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The area of Circle is 78.5
    The area of Rectangle is 50
    

    This way, you can define the same method with different functionalities and invoke a particular one according to the required functionalities.

    You can also call the parent class method in the child class using the super keyword. Let's understand it via the example below.

    Example 2: Parent Class Method's Functionality Extension in Child Class

    The Math and AdvanceMath class contains the mathOperations() method in the example below.

    In the mathOperations() method of the AdvanceMath class, we used the super keyword to invoke the mathOperations() method of the parent class. We extend the functionality of the math class's mathOperations() method in the AdvanceMath class's mathOperations() method.

    Also, when you invoke the mathOperation() method using the object of the Math class, it invokes the method of the Math class only.

    <html><body><p id ="output1"></p><p id ="output2"></p><script>classMath{mathOperations(a, b){
    
       document.getElementById("output1").innerHTML ="Addition: "+(a+b)+"&lt;br&gt;";
       document.getElementById("output1").innerHTML +="Subtraction: "+(a-b);}}classAdvanceMathextendsMath{mathOperations(a, b){super.mathOperations(a, b);
       document.getElementById("output2").innerHTML +="Multiplication: "+(a*b)+"&lt;br&gt;";
       document.getElementById("output2").innerHTML +="Division: "+(a/b);}}const A_math =newAdvanceMath();
    A_math.mathOperations(10,5);// Calls method of AdvanceMath class</script></body></html>

    Output

    Addition: 15
    Subtraction: 5
    
    Multiplication: 50
    Division: 2
    

    This type of polymorphism is called runtime polymorphism, as the JavaScript engine decides which method it should execute at the run time based on which class's instance is used.

    Benefits of using Polymorphism in JavaScript

    There are many advantages to using polymorphism in JavaScript; we have explained some of them here.

    • Code reusability − Polymorphism allows you to reuse the code. In the second example, we have reused the code of the mathOperations() method of the math class.
    • Extensibility − You can easily extend the current code and define new functionalities.
    • Dynamic behaviors − You can have multiple classes containing the same method with different functionalities and call the method of the particular class dynamically at the run time.

    You can't achieve the compile time polymorphism in JavaScript as you can't overload the method.

  • Abstraction

    Abstraction in JavaScript

    The Abstraction in JavaScript can be achieved using the abstract class. In object-oriented programming, the abstraction concept allows you to hide the implementation details and expose features only to the users.

    For example, you can execute the Math object methods in JavaScript by accessing the method using its name but cant see how it is implemented. Same way array methods like push(), pop(), etc., can be executed, but you dont know how it is implemented internally.

    So, the abstraction makes code cleaner by exposing the required features and hiding the internal implementation details.

    How to Achieve Abstraction in JavaScript?

    In most programming languages, you can achieve abstraction using the abstract class. The abstract class contains only method declaration but not implementation. Furthermore, you need to implement the methods declared in the abstract class into the child class. Also, you cant create an instance of the abstract class.

    JavaScript doesnt allow to create an abstract class like Java or CPP natively, but you can achieve the same functionality using the object constructor function.

    First, lets create an abstract class using the example below.

    Creating the Abstract Class

    In the below example, the fruit() function initializes the name property. When anyone creates an instance of the fruit(), the value of the constructor property becomes equal to the fruit. So, we throw an error to prevent creating an instance of the fruit.

    Also, we have added the getName() method to the prototype. After that, we create an instance of the fruit() constructor, and you can observe the error in the output.

    <html><body><div id ="output"></div><script>try{// Object constructorfunctionfruit(){this.name ="Fruit";if(this.constructor === fruit){// Preventing the instance of the objectthrownewError("You can't create the instance of the fruit.");}}// Implementing method in the prototype
    
         fruit.prototype.getName=function(){returnthis.name;}const apple =newfruit();}catch(error){
         document.getElementById("output").innerHTML = error;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Error: You can't create the instance of the fruit.
    

    In the above example, you learned to achieve the abstract class functionality.

    Now, you will learn to extend the abstract class and implement the methods defined in the abstract class via the example below.

    Extending the Abstract Class

    In the example below, fruit() constructor is similar to the above example. We have implemented the Apple() constructor, initializing the name property.

    After that, we assign the prototype of the fruit() function to the Apple() function using the Object.create() method. It means Apple() function inherits the properties and methods of the fruit() class.

    After that, we have created the instance of the Apple() class and invoked the getName() method.

    <html><body><div id ="output">The name of the fruit is:</div><script>// Abstract classfunctionfruit(){this.name ="Fruit";if(this.constructor === fruit){// Preventing the instance of the objectthrownewError("You can't create the instance of the fruit.");}}// Implementing method in the prototype
    
      fruit.prototype.getName=function(){returnthis.name;}// Child classfunctionApple(fruitname){this.name = fruitname;}// Extending the Apple class with the fruit classApple.prototype = Object.create(fruit.prototype);const apple =newApple("Apple");
      document.getElementById("output").innerHTML += apple.getName();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The name of the fruit is: Apple
    

    The prototype implements the getName() method in the above code. So, it is hidden.

    This way, you can use an object constructor to achieve abstraction in JavaScript.

  • Inheritance

    Inheritance in JavaScript

    The concept of inheritance in JavaScript allows the child class to inherit the properties and methods of the parent class. Inheritance is also a fundamental concept of object-oriented programming like encapsulation and polymorphism.

    Sometimes, you must add the properties and methods of the one class into another. For example, you have created a general class for the bike containing the same properties and methods for each bike. After that, you create a separate class for the bike “Honda”, and you need to add all properties and methods to the “Honda” class. You can achieve it using inheritance.

    Before ECMAScript 6 (ES6), the object’s prototype was used for inheritance, but in ES6, the ‘extends’ keyword was introduced to inherit classes.

    The following terminologies are used in this chapter.

    • Parent class − It is a class whose properties are inherited by other classes.
    • Child class − It is a class that inherits the properties of the other class.

    JavaScript Single Class Inheritance

    You can use the ‘extends‘ keyword to inherit the parent class properties into the child class. In single class inheritance only a single class inherits the properties of another class.

    Syntax

    You can follow the syntax below for the single-class inheritance.

    classchildClassextendsparentClass{// Child class body}

    In the above syntax, you can replace the ‘childClass’ with the name of the child class and ‘parentClass’ with the name of the parent class.

    Example: Single Class Inheritance

    In the example below, the ‘Bike’ class is a parent class, and the ‘Suzuki’ class is a child class. The suzuki class inherits the properties of the Bike class.

    The Bike class contains the constructor() method initializing the gears property and the getGears() method returning the value of the gears property.

    The suzuki class contains the constructor() method to initialize the brand property and getBrand() method, returning the value of the brand property.

    We have created an object of the ‘suzuki’ class. Using the ‘suzuki’ class instance, we invoke the getBrand() and getGears() methods.

    <html><body><div id ="output1">The brand of the bike is:</div><div id ="output2">Total gears in the bike is:</div><script>// Parent classclassBike{constructor(){this.gear =5;}getGears(){returnthis.gear;}}// Child classclasssuzukiextendsBike{constructor(){super();this.brand ="Yamaha"}getBrand(){returnthis.brand;}}const suzukiBike =newsuzuki();
    
      document.getElementById("output1").innerHTML += suzukiBike.getBrand();
      document.getElementById("output2").innerHTML += suzukiBike.getGears();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The brand of the bike is: Yamaha
    Total gears in the bike is: 5
    

    In this way, you can use the properties and methods of the parent class through the instance of the child class.

    JavaScript super() Keyword

    In the above example, we have initialized the 'gear' property of the Bike class with a static value. In real life, you need to initialize it with the dynamic value according to the model of the bike.

    Now, the question is how to initialize the properties of the parent class from the child class. The solution is a super() keyword.

    The super() keyword is used to invoke the method or access the properties of the parent class in the child class. By default, the super() keyword invokes the constructor function of the parent class. You can also pass the parameters to the super() keyword to pass it to the constructor of the parent class.

    Example: Using super() keyword to initialize the parent class properties

    In the example below, suzuki class extends the Bike class.

    The Bike class contains the constructor, taking gears as parameters and, using it, initializes the gears property.

    The 'suzuki' class also contains the constructor, taking a brand and gears as a parameter. Using the brand parameter, it initializes the brand property and passes the gears parameter as an argument of the super() keyword.

    After that, we create an object of the 'suzuki' class and pass the brand and gears as an argument of the constructor. You can see the dynamic value of the brand and gear property in the output.

    <html><body><div id ="output1">The brand of the bike is:</div><div id ="output2">Total gears in the bike is:</div><script>// Parent classclassBike{constructor(gears){this.gears = gears;}}// Child classclasssuzukiextendsBike{constructor(brand, gears){super(gears);this.brand = brand;}}const suzukiBike =newsuzuki("Suzuki",4);
    
      document.getElementById("output1").innerHTML += suzukiBike.brand;
      document.getElementById("output2").innerHTML += suzukiBike.gears;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The brand of the bike is: Suzuki
    Total gears in the bike is: 4
    

    In this way, you can dynamically initialize the properties of the parent class from the child class.

    JavaScript Multilevel Inheritance

    Multilevel inheritance is a type of inheritance in JavaScript. In multilevel inheritance, one class inherits the properties of another class, and other classes inherit current class properties.

    Syntax

    Users can follow the syntax below for the multilevel inheritance.

    classA{}classBextendsA{}classCextendsB{}

    In the above syntax, the C class inherits the B class, and the B class inherits the A class.

    Example

    In the example below, the Honda class inherits the Bike class. The Shine class inherits the Honda class.

    We use the super() keyword in each class to invoke the parent class's constructor () and initialize its properties.

    We are accessing the properties of the Bike class using the instance of the Shine class, as it indirectly inherits the properties of the Bike class.

    <html><body><p id ="output"></p><script>// Parent classclassBike{constructor(gears){this.gears = gears;}}// Child classclassHondaextendsBike{constructor(brand, gears){super(gears);this.brand = brand;}}classShineextendsHonda{constructor(model, brand, gears){super(brand, gears);this.model = model;}}const newBike =newShine("Shine","Honda",5);
    
      document.getElementById("output").innerHTML =The ${newBike.model} model of the ${newBike.brand} brand has total ${newBike.gears} gears.;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The Shine model of the Honda brand has total 5 gears.
    

    JavaScript Hierarchical Inheritance

    In JavaScript hierarchical inheritance, one class is inherited by multiple classes.

    Syntax

    The syntax of JYou can follow the syntax below for the hierarchical inheritance.

    classA{}classBextendsA{}
    Class CextendsA{}

    In the above syntax, B and C both classes inherit the properties of the A class.

    Example

    In the example below, the Bike class contains the gears property and is initialized using the constructor() method.

    The Honda class extends the Bike class. The constructor() method of the Honda class initializes the properties of the Bike class using the super() keyword and model property of itself.

    The Suzuki class inherits the Bike class properties. The constructor() method of the Suzuki class also initializes the Bike class properties and the other two properties of itself.

    After that, we create objects of both Honda and Suzuki classes and access their properties.

    <html><body><p id ="output1"> Honda Bike Object:</p><p id ="output2"> Suzuki Bike Object:</p><script>// Parent classclassBike{constructor(gears){this.gears = gears;}}// Child classclassHondaextendsBike{constructor(model, gears){super(gears);this.model = model;}}// Child classclassSuzukiextendsBike{constructor(model, color, gears){super(gears);this.model = model;this.color = color;}}const h_Bike =newHonda("Shine",5);const s_Bike =newSuzuki("Zx6","Blue",6);
    
      document.getElementById("output1").innerHTML +=JSON.stringify(h_Bike);
      document.getElementById("output2").innerHTML +=JSON.stringify(s_Bike);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Honda Bike Object: {"gears":5,"model":"Shine"}
    
    Suzuki Bike Object: {"gears":6,"model":"Zx6","color":"Blue"}
    

    Inheriting Static Members of the Class

    In JavaScript, you can invoke the static methods of the parent class using the super keyword in the child class. Outside the child class, you can use the child class name to invoke the static methods of the parent and child class.

    Example

    In the example below, the Bike class contains the getDefaultBrand() static method. The Honda class also contains the Bikename() static method.

    In the Bikename() method, we invoke the getDefaultBrand() method of the parent class using the 'super' keyword.

    Also, we execute the Bikename() method using the 'Honda' class name.

    <html><body><p id ="output">The bike name is:</p><script>// Parent classclassBike{constructor(gears){this.gears = gears;}staticgetDefaultBrand(){return"Yamaha";}}// Child classclassHondaextendsBike{constructor(model, gears){super(gears);this.model = model;}staticBikeName(){returnsuper.getDefaultBrand()+", X6";}}
    
      document.getElementById("output").innerHTML += Honda.BikeName();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The bike name is: Yamaha, X6
    

    When you execute any method using the 'super' keyword in the multilevel inheritance, the class finds the methods in the parent class. If the method is not found in the parent class, it finds in the parent's parent class, and so on.

    JavaScript Prototype Based Inheritance

    You can also update or extend the prototype of the class to inherit the properties of the multiple classes to the single class. So, it is also called multiple inheritance.

    Syntax

    You can follow the syntax below to use prototype-based inheritance.

    Child.prototype = Instance of parent class

    In the above syntax, we assign the parent class instance to the child object's prototype.

    Example: JavaScript Prototype Based Inheritance

    In the example below, Bike() is an object constructor that initializes the brand property.

    After that, we add the getBrand() method to the prototype of the Bike() function.

    Next, we have created the Vehicle() object constructor and instance of the Bike() constructor.

    After that, we update the prototype of the Vehicle class with an instance of the Bike. Here, Vehicle works as a child class and Bike as a parent class.

    We access the getBrand() method of the Bike() function's prototype using the instance of the Vehicle () function.

    <html><body><p id ="output1">Bike brand:</p><p id ="output2">Bike Price:</p><script>functionBike(brand){this.brand = brand;}Bike.prototype.getBrand=function(){returnthis.brand;}//Another constructor function  functionVehicle(price){this.price = price;}const newBike =newBike("Yamaha");Vehicle.prototype = newBike;//Now Bike treats as a parent of Vehicle.  const vehicle =newVehicle(100000);
    
    
      document.getElementById("output1").innerHTML += vehicle.getBrand();
      document.getElementById("output2").innerHTML += vehicle.price;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Bike brand: Yamaha
    
    Bike Price: 100000
    

    You can't access the private members to the parent class in the child class.

    Benefits of Inheritance

    Here, we will learn the benefits of the inheritance concept in JavaScript.

    • Code reusability − The child class can inherit the properties of the parent class. So, it is the best way to reuse the parent class code.
    • Functionality extension − You can add new properties and methods to extend the parent class functionality in each child class.
    • Code maintenance − It is easier to maintain a code as you can divide the code into sub-classes.
    • Multilevel and hierarchical inheritance allows you to combine data together.