Blog

  • Versions

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

    The latest version of JavaScript is ECMAScript 2023.

    JavaScript Versions

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

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

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

  • History

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

    History of JavaScript

    Let’s discuss a brief history of JavaScript.

    First stage development of JavaScript

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

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

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

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

    Standardization of JavaScript

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

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

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

    The latest version of JavaScript is ES13.

    JavaScript Libraries and Frameworks

    After 2005, a revolution came into JavaScript development.

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

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

    Server-side JavaScript

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

    Currently, Google is managing NodeJS.

    Modern JavaScript and ES6 Release

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

    The latest version of JavaScript Es13 was released in 2022.

    History table of JavaScript

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

    Future of JavaScript

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

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

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

  • Proxies

    Proxy in JavaScript

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

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

    Syntax

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

    const obj =newProxy(targetObj, Handler);

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

    Parameters

    The Proxy constructor takes two parameters.

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

    Example

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

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

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

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

    Output

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

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

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

    JavaScript Proxy Handlers

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

    The JavaScript get() proxy handler

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

    Syntax

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

    get(target, property, receiver)

    Parameters

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

    Example

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

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

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

    Output

    Brand: Casio
    Price: Property is null.
    

    The JavaScript set() proxy handler

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

    Syntax

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

    set(target, property, value, receiver)

    Parameters

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

    Example

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

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

    Output

    Price: 2000
    Dial: Not Available
    

    The JavaScript apply() proxy handler

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

    Syntax

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

    apply(target, thisArg, arguments)

    Parameters

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

    Example

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

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

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

    Output

    BRAND: CASIO, COLOR: BLUE, PRICE: 2000
    

    Uses of the Proxy Object in JavaScript

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

    For Validation

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

    Example

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

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

    Output

    num1: 20, num2: 20
    

    For Access Control

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

    Example

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

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

    Output

    Object is read-only.
    num1: 10
    

    Side Effects

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

    Example

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

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

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

    Output

    email1: [email protected]
    

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

    JavaScript Proxy Handlers List

    Here, we have listed all proxy handlers in JavaScript.

    Proxy Handler Methods

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

    Constructor

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

    Static Method

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

    Mixins in JavaScript

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

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

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

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

    JavaScript Mixins with Objects

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

    Syntax

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

    Object.assign(target, obj);

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

    Parameters

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

    Example

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

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

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

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

    Output

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

    JavaScript Mixins with Classes

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

    Syntax

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

    Object.assign(class_name.prototype, obj);

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

    Example

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

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

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

    Output

    Cat eats: true
    Animals run.
    

    Achieving Multiple Inheritance Using the Mixins

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

    Syntax

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

    Object.assign(target, ob1, obj);

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

    Example: Inheriting multiple objects

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

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

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

    Output

    Person is eating the food!
    Person is drinking water!
    

    Example: Multiple Inheritance with Classes

    The below example demonstrates extending one class with multiple classes.

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

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

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

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

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

    Output

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

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

    Benefits of using Mixins

    Here, we have listed some benefits of using mixins.

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

    Limitations of Mixins

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

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

    Global Objects in JavaScript

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

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

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

    Syntax

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

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

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

    Examples

    Example: Accessing global variables through the global object

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

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

    Output

    The company name is: Tutorialspoint
    

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

    Example: Accessing the global function through the global object

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

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

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

    Output

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

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

    Let's look at the example below.

    Example: Making variable globally accessible from the function scope

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

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

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

    Output

    The sum is: 50
    

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

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

    Example: Accessing pre-defined methods of the global object

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

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

    Output

    Is hello not a number? true
    

    Using the JavaScript Global Object for Polyfills

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

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

    Example

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

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

    Output

    Your browser supports promises
    

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

  • Optional Chaining

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

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

    The Non-existing Property Problem

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

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

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

    For example,

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

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

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

    Uncaught TypeError: Cannot read properties of undefined
    

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

    For example,

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

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

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

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

    What is an Optional Chaining in JavaScript?

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

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

    Syntax

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

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

    Return value

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

    Example

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

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

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

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

    Output

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

    Optional Chaining with Function Calls

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

    Example

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

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

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

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

    Output

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

    Optional Chaining with Expression

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

    Example

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

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

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

    Output

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

    Optional Chaining with the "delete" Operator

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

    Example

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

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

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

    Output

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

    Short-circuiting with Optional Chaining

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

    Example

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

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

    Output

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

    Nullish Coalescing Operator with Optional Chaining

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

    Example

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

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

    Output

    The color of the animal is: Red
    

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

  • Nested Destructuring

    Nested Destructuring

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

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

    Nested Object Destructuring

    This section will demonstrate nested object destructuring in JavaScript.

    Syntax

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

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

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

    Example

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

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

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

    Output

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

    Example: Nested object destructuring and renaming variables

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

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

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

    Output

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

    Example: Nested object destructuring and default values

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

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

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

    Output

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

    Example: Nested object destructuring and rest operator

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

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

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

    Output

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

    Nested Array Destructuring

    This section will demonstrate nested array destructuring in JavaScript.

    Syntax

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

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

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

    Example

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

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

    Output

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

    Example: Skipping elements of the nested array

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

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

    Output

    a = 2, b = 4, c = 10
    

    Example: Nested array destructuring and default values

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

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

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

    Output

    p = 29, q = 10
    

    Example: Nested array destructuring and rest operator

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

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

    Output

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

    Array Within Object Nested Destructuring

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

    Example

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

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

    Output

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

    Object Within Array Nested Destructuring

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

    Example

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

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

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

    Output

    a = 10, p = 20, q = 30

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