Blog

  • 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.
  • Encapsulation

    What is Encapsulation?

    Encapsulation in JavaScript is a way to keep the related properties and methods under a single namespace by bundling them. It can be a function, a class or an object. In JavaScript, the encapsulation can be implemented using closures, classes and getters and setters.

    Encapsulation is a fundamental concept in Object-oriented programming languages, along with inheritance and polymorphism. JavaScript is an object oriented programming language.

    It is used to hide the data from the outside world and give access to required data only to improve the integrity and security of the data.

    What is the need for encapsulation?

    Let’s discuss the need for encapsulation in JavaScript via the following example.

    For example, you have defined the below object in your code.

    const car ={
       Brand:"Honda city",
       model:"sx",
       year:2016,}

    Anyone can access the properties of the car object, as shown below.

    car.Brand
    

    Also, anyone can change the value of any property of the car object, as shown below.

    car.Brand =true;

    Here, the value of the Brand property is changed to the boolean from the string. So, it is required to secure the original data of the object and give limited access to the data to the outside world.

    In this situation, the concept of encapsulation comes into the picture.

    Different Ways to Achieve Encapsulation in JavaScript

    There are three different ways to achieve encapsulation.

    • Using the function closures
    • Using the ES6 classes
    • Using the Getters and Setters

    Here, we will learn each approach for achieving encapsulation one by one.

    Achieving Encapsulation Using the Function Closures

    A JavaScript function closure is a concept allowing the inner function to access the variable defined in the outer function even after the outer function is executed. The variables defined in the outer function can’t be accessed outside its functional scope but can be accessed using the inner scope.

    Example

    In the below code, shoppingCart() function is an outer function that contains the variables and function. The outer function has its private scope.

    The carItems[] array is used to store the shopping cart’s items.

    The add() function can access the carItems[] array and add items.

    The remove() function checks whether the cartItems[] contains the items you need to remove. If yes, it removes the item. Otherwise, it prints the message that you can’t remove the item.

    The shoppingCart() function returns the object containing the add() and remove() functions.

    After creating a new instance of the shoppingCart() function, you can use the add() and remove() functions to manipulate the shopping cart data.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");functionshoppingCart(){const cartItems =[];functionadd(item){
    
        cartItems.push(item);
        output.innerHTML +=${item.name} added to the cart. &amp;lt;br&amp;gt;;}functionremove(itemName){const index = cartItems.findIndex(item=&gt; item.name === itemName);if(index !==-1){const removedItem = cartItems.splice(index,1)[0];
          output.innerHTML +=${removedItem.name} removed from the cart. &amp;lt;br&amp;gt;;}else{
          output.innerHTML +=Item ${itemName} not found in the cart. &amp;lt;br&amp;gt;;}}return{
        add,
        remove,};}// Defining itemsconst item1 ={ name:'Car', price:1000000};const item2 ={ name:'Bike', price:100000};// Create a new Shopping cartconst cart =shoppingCart();// Adding items to the cart
    cart.add(item1);
    cart.add(item2);// Remove bike from the cart
    cart.remove('Bike');&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Car added to the cart.
    Bike added to the cart.
    Bike removed from the cart.
    

    In this way, no one can directly access and modify the cartItems[] array.

    Achieving Encapsulation Using ES6 Classes and Private Variables

    In JavaScript, you can use classes and private variables to achieve the encapsulation.

    Private Variables (Fields) in JavaScript

    To define the private class variables, you can write a variable name followed by the # sign. For example, 'name' is a private variable in the below code.

    classcar{
    
    #name="TATA";}</pre>

    If you try to access the name by the instance of the class, it will give you an error that private fields can't be accessed outside the class.

    To achieve encapsulation, you can define the private variables in the class and give them access to the outside world using different methods.

    Example

    In the example below, we have defined the car class.

    The car class contains the 'brand', 'name', and 'milage' private variables.

    The getMilage() method is defined to return the milage of the car, and the setMilage() method is used to set the milage of the method.

    We created the car class's object and used the method to access and modify the private fields. If you try to access the private field of the class, the code will throw an error.

    You can also define more methods in the class to access and modify other private fields.

    <html><body><div id ="output1">The car mileage is:</div><div id ="output2">After updating the car mileage is:</div><script>classCar{
    
      #brand ="TATA";// Private field
      #name ="Nexon";// Private field
      #milage =16;// Private fieldgetMilage(){returnthis.#milage;// Accessing private field}setMilage(milage){this.#milage = milage;// Modifying private field}}let carobj =newCar();
    document.getElementById("output1").innerHTML += carobj.getMilage();
    carobj.setMilage(20);
    document.getElementById("output2").innerHTML += carobj.getMilage();// carobj.#milage);  will throw an error.&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The car mileage is: 16
    After updating the car mileage is: 20
    

    Achieving Encapsulation Using the Getters and Setters

    The JavaScript getters and setters can be defined using the get and set keywords, respectively. The getters are used to get the class properties, and setters are used to update the class properties.

    They are very similar to the class methods but defined using the get/set keyword followed by the method name.

    Example

    In the example below, we have defined the User class containing the three private fields named username, password, and isLoggedIn.

    The getters and setters named username are defined to get and set user names. Here, you can observe that name of the getters and setters method is the same.

    After that, we create an object of the class and use the getters and setters as the property to access and update the username field of the class.

    You may also create getters and setters for the other class fields.

    <html><body><div id ="output1">The initial username is:</div><div id ="output2">The newusername is:</div><script>classUser{
    
            #username ="Bob";
            #password ="12345678";
            #isLoggedIn =false;getusername(){returnthis.#username;}setusername(user){this.#username = user;}}const user =newUser();
        document.getElementById("output1").innerHTML += user.username;
        user.username ="Alice";
        document.getElementById("output2").innerHTML += user.username;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The initial username is: Bob
    The new username is: Alice
    

    From the above all, you can understand that encapsulation is making variable privates and restricting its access to the outside world.

    Benefits of Encapsulation in JavaScript

    Here, we have listed some benefits of encapsulation in JavaScript −

    • Data protection − The encapsulation allows you to control the access of the class data by making them private. You can expose the required data and methods only. So, no one can modify the data by mistake. Also, you can validate the data while updating them. If new data is not valid, you can throw an error.
    • Code reusability − The class is a template for the object, and you can reuse it to create objects with different data.
    • Code Maintenance − The encapsulation makes it easy to maintain the code as each object is independent, and if you make changes to one object, it doesn't affect the other code.
  • ES5 Object Methods

    The ES5 Object methods in JavaScript are used to manipulate and protect the obejcts. ECMAScript 5 (ES5) is a significant revision of the language introduced in 2009. It has added many object methods to JavaScript.

    These methods provide us with efficient ways to iterate through object properties, manipulate values, and perform various operations on objects. Object manipulation is a fundamental aspect of JavaScript programming.

    JavaScript ES5 Object Methods

    In ES5, object-related methods are added to manipulate and protect the objects. The following tables highlight the object methods and their descriptions −

    Methods to Manipulate the Object

    JavaScript contains built-in constructors, which we have listed in the below table.

    Sr.No.MethodDescription
    1create()To create new objects with specified prototype object.
    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.

    Let’s undertand each of the methods listed above with the help of some examples −

    JavaScript Object.create() Method

    The JavaScript Object.create() method creates a new object with the specified prototype object and properties. It is a static method in JavaScript.

    The syntax of the Object.create() method in JavaScript is as follows

    Object.create(proto, propertiesObject)

    The paramters in the Object.create() method are as follows −

    • proto − it is the object that is used as prototype of new object.
    • propertiesObejct (optaional) − It’s an object that defines the properties of new object.

    Example

    In the example below, the student object is created using the person object as it’s prototype.

    <html><body><div id ="output"></div><script>const person ={
    
      firstName:"John",
      lastName:"Doe"};const student = Object.create(person);
    student.age =18;
    
    document.getElementById("output").innerHTML = 
    student.firstName +"&lt;br&gt;"+
    student.lastName +"&lt;br&gt;"+
    student.age;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    John
    Doe
    18
    

    JavaScript Object.defineProperty() Method

    You can use the Object.definedProperty() method to define a single property of the object or update the property value and metadata. It's a static method in JavaScript.

    The syntax of the Object.definedProperty() method in JavaScript is as follows −

    Object.defineProperty(obj, prop, descriptor)

    The paramters in the Object.definedProperty() method are as follows −

    • obj − it is the object on which the property is to be defined or modified.
    • prop (string or symbol) − It's the name of property to be defined or modified.
    • descriptor − It's an object that defines the property's attributes.

    Example

    The below example 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 Object.defineProperties() Method

    The Object.defineProperties() method in JavaScript is a static method that defines new properties of object or modifies the properties.

    The syntax of Object.defineProperties() method in JavaScript is as follows

    Object.defineProperties(obj, props)

    The parameters in the Object.defineProperties() method are as follows −

    • obj − it is the object on which the properties are to be defined or modified.
    • prop (string or symbol) − It's the name of property to be defined or modified.

    Example

    In the following example, we use Object.defineProperties() method to add two mew properties named property1 and property2. The property1 is writable and property2 is non-writable.

    <html><body><div id ="output"></div><script>const object1 ={};
    
    
    Object.defineProperties(object1,{
      property1:{
        value:42,
        writable:true,},
      property2:{
      value:"Tutorials Point",
      writable:false,},});
    document.getElementById("output").innerHTML ="Property1 : "+ object1.property1 +"&lt;br&gt;"+"Property2 : "+ object1.property2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Property1 : 42
    Property2 : Tutorials Point
    

    JavaScript Object.getOwnPropertyDescriptor() Method

    The Object.getOwnPropertyDescriptor() method in JavaScript returns a property descriptor for a specific property of an object. The returned property descriptor is a JavaScript object.

    Example

    Try the following example −

    <html><body><div id ="output"></div><script>const object1 ={
    
      property1:42,};const descriptor1 = Object.getOwnPropertyDescriptor(object1,'property1');
    document.getElementById("output").innerHTML ="descriptor configurable? : "+ descriptor1.configurable +"&lt;br&gt;"+"descriptor value : "+ descriptor1.value;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    descriptor configurable? : true
    descriptor value : 42
    

    JavaScript Object.getOwnPropertyNames() Method

    The Object.getOwnPropertyNames() method in JavaScript returns an array of all the properties found in a given object. This includes both enumerable and non-enumerable properties.

    Example

    In the example below, we use getOwnPropertyNames() method to get the property names of the created object.

    <html><body><div id ="output"></div><script>const obj ={
    
      a:10,
      b:20,
      c:30,};
    document.getElementById("output").innerHTML = Object.getOwnPropertyNames(obj);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a,b,c
    

    JavaScript Object.getPrototypeOf() Method

    The Object.getPrototypeOf() method in JavaScript returns the prototype of the specified object. It's a static JavaScript method added in ES5.

    Example

    <html><body><div id ="output"></div><script>const prototype1 ={name:"John Doe"};const object1 = Object.create(prototype1);const prot = Object.getPrototypeOf(object1)
    
    document.getElementById("output").innerHTML =JSON.stringify(prot);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    {"name":"John Doe"}
    

    JavaScrip Object.keys() Method

    The Object.keys() method in javaScript takes an object as an argument and returns an array containing the object's own enumerable property names.

    <html><body><div id ="output"></div><script>let person ={
    
       name:"John Doe",
       age:20,
       profession:"Software Engineer"};
    document.getElementById("output").innerHTML = Object.keys(person);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    name,age,profession
    

    JavaScript Object.freeze() Method

    The Object.freeze() in JavaScript is static method that freezes an object. A frozen object can not be further changed. No new property can be added or the existing properties can not be removed. The values of the properties can not be modified.

    <html><body><div id ="output"></div><script>const obj ={
    
      prop:23,};
    Object.freeze(obj);// obj.prop = 33;// Throws an error in strict mode
    document.getElementById("output").innerHTML = obj.prop;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    23
    

    JavaScript Object.seal() Method

    The Object.seal() static method seals an object. In a sealed object, no new property can be added, no property can be deleted.

    <html><body><div id ="output"></div><script>const obj ={
    
      property:34,};
    Object.seal(obj);
    obj.property =33;
    document.getElementById("output").innerHTML = obj.property;delete obj.property;// Cannot delete when sealed
    
    document.getElementById("output").innerHTML = obj.property;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    33
    

    JavaScript Object.isFrozen() Method

    The Object.isFrozen() method in JavaScript returns true if the given object is frozen, else it returns false if the object is not frozen.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>const person ={
    
      age:21,};
    document.getElementById("output1").innerHTML = Object.isFrozen(person);// Expected output: false
    Object.freeze(person);
    document.getElementById("output2").innerHTML += Object.isFrozen(person);// Expected output: true&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    false
    true
    

    JavaScript Object.isSealed() Method

    The Object.isSeal() method in JavaScript is used to check if the given object is sealed or not. It returns true if the object is sealed else it retuens flase.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>const person ={
    
      name:"John Doe",};
    document.getElementById("output1").innerHTML = Object.isFrozen(person);// Expected output: false
    Object.seal(person);
    document.getElementById("output2").innerHTML += Object.isSealed(person);// Expected output: true&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    false
    true
    

    JavaScript Object.preventExtensions() Method

    The ES5 Object.preventExtensions() method is used to prevent the prototype updation of an object. It also prevent the new properties to be added to an object.

    <html><body><div id ="output"></div><script>const person ={};
    
    Object.preventExtensions(person);try{
      Object.defineProperty(person,'name',{
        value:"John Doe",});}catch(e){
      document.getElementById("output").innerHTML =e;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    It will produce the following output −

    TypeError: Cannot define property name, object is not extensible
    

    JavaScript Object.isExtensible() Method

    The JavaScript Object.isExtensible() method is used to check if an object is extensible or not. It returns true indicating the given object is extensible, else it will return false. An object is extensible if it can have new properties added to it.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>const person ={
    
      name:"John Doe",};
    
    document.getElementById("output1").innerHTML = Object.isExtensible(person);// Expected output: false
    Object.preventExtensions(person);
    document.getElementById("output2").innerHTML += Object.isExtensible(person);// Expected output: false&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    true
    false

  • Native Prototypes

    Native Prototypes

    The native prototypes in JavaScript are property of Object.prototype object. The prototypes are the mechanism by which the objects inherit features from one another.

    In JavaScript, each object contains the prototype property. The prototype of each object contains the methods and properties related to the object. So, it is also called the native prototype.

    However, you can update or add new methods and properties to the native prototype object, but you can’t delete any already existing.

    The JavaScript object and object constructor are the main prerequisites to understand JavaScript native prototypes.

    Syntax

    You can follow the syntax below to access the native prototype of the object.

    Object.prototype;

    In the above syntax, the object can be any JavaScript object.

    Example: Accessing the array’s prototype

    Whenever you execute the below code in the browser, it will print the prototype of the array in the browser console. In the same way, you can check the prototype of the other objects.

    In the console, you can see that the prototype object contains the methods which you can use with array methods.

    <html><body><script>
    		console.log(Array.prototype);</script><p>Please open the web console before executing the above program.</p></body></html>

    Output

    On running the above program, you will see the result in web console similar to the following screenshot −

    JavaScript Array Prototype

    Updating the Native Prototype

    You can update the existing method or property of the native prototype object or add a new method or property to the native prototype object.

    Syntax

    You can follow the syntax below to update or add new properties or methods to the prototype object.

    objName.prototype.name = value
    

    In the above syntax, objName is an object whose prototype you need to update.

    The ‘name’ is a method or property name. You can assign new values or function expressions to the ‘name.

    Example: Updating the toLowerCase() method of the string object’s prototype

    The prototype of the String object contains the toLowerCase() method. Here, we update the toLowerCase() method.

    The updated toLowerCase() method returns the string in the uppercase. In the output, you can observe the string, which is in uppercase.

    In this way, you can update the functionality of the built-in methods of the object.

    <html><body><p id ="output">After updating the string.toLowerCase() method:</p><script>String.prototype.toLowerCase=function(){returnthis.toUpperCase();}let str ="Hello World";
    		document.getElementById("output").innerHTML += str.toLowerCase();</script></body></html>

    Output

    After updating the string.toLowerCase() method: HELLO WORLD
    

    You shouldn’t update the methods and properties of the native prototype object. However, you can add new as shown in the example below.

    Example: Adding a new method to the prototype object

    You can also add a new method to the Object prototype. Here, we added the firstCase() method in the object prototype.

    The firstCase() method returns a string after converting the string’s first character to the uppercase.

    <html><body><p id ="output">After executing the string.firstCase() method:</p><script>String.prototype.firstCase=function(){// First character in uppercase. Other characters in lowercase.returnthis.charAt(0).toUpperCase()+this.slice(1).toLowerCase();}let str ="hello world";
    		document.getElementById("output").innerHTML += str.firstCase();</script></body></html>

    Output

    After executing the string.firstCase() method: Hello world
    

    Adding a method to the constructor function

    Whenever you define an object using the constructor function, you can’t add a method or property to the constructor function using its instance. So, you need to add the method to the constructor function prototype. So it can be accessible through all instances of the object.

    Example

    In the example below, the Person() is a constructor function that initializes object properties.

    After that, we added the display() method to the prototype of the person() function.

    Next, we created two instances of the Person() function and used the display() method with them. So, methods and properties added in the prototype of the object constructor can be accessed through all instances of the constructor function.

    <html><body><p id ="demo"></p><script>const output = document.getElementById("demo");functionPerson(id, name){this.id = id;this.name = name;}Person.prototype.display=function(){
    			output.innerHTML +=this.id +", "+this.name +"<br>";}const p1 =newPerson(1,"James");const p2 =newPerson(2,"Nayan");
    		p1.display();
    		p2.display();</script></body></html>

    Output

    1, James
    2, Nayan
    

    All instances of the object inherit the properties and methods from their parent’s prototype.

    JavaScript Prototype Chaining

    Simply, you can say that the prototype stores the default values of the properties. The code overrides the prototype property value if the object constructor and its prototype contain the same properties.

    Example

    In the below code, the Person() function contains the name property. We have added the name and age property in the function’s prototype.

    We have created the p1 object using the Person() constructor function. The value of the name property of the p1 object is ‘Nayan’ as the name already exists in the constructor. The value of the age property is 20, which is the same as the age property value in the prototype.

    <html><body><p id ="output"></p><script>functionPerson(id, name){this.id = id;this.name = name;}Person.prototype.name ="John";Person.prototype.age =20;const p1 =newPerson(1,"Adam");
    		document.getElementById("output").innerHTML ="Id: "+ p1.id +", Name: "+ p1.name +", Age: "+ p1.age;</script></body></html>

    Output

    Id: 1, Name: Adam, Age: 20