How to Destructure Object in Javascript

In this tutorial, you will learn how to destructure object in javascript. Object destructuring is one of the most commonly used ES6 (ECMAScript 6) javascript features. With the help of object destructuring, you can extract properties from an object with a single line of code.

A property in the object is just a key-value pair. While destructuring an object, the variable name and key name should be the same. But if you are planning to use a different variable name, then you can provide an alias.

You can also assign a default value to the variable if a property does not even exist. I suggest you to have a look over MDN docs to get more detailed information about object destructuring since we are not going to cover much in this tutorial.

In the following example, we will destructure an object, form a template string and display that on the screen. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The button element and the h1 element have “Get” and “Result” as innerText respectively.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button>Get</button>
        <h1>Result</h1>
    </div>
    
    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected the button and h1 elements using the document.querySelector() method and stored them in the btnGet and result variables respectively.
  • We have attached a click event listener to the button element.
  • In the event handler function, we have a local users object.
  • We destructured the user object and as a result, we got 4 variables a, b, c, and d. As you can see, there is no property by key name d, so we have created an alias d1 for d and also assigned a default value “Rita” to it.
  • We are forming a template string using all variables and displaying that in the h1 element using the innerText property.
let btnGet = document.querySelector('button');
let result = document.querySelector('h1');

btnGet.addEventListener('click', () => {
    let users = {
        a: 'Marks',
        b: 'James',
        c: 'Peter',        
    };

    let {a, b, c, d:d1 = 'Rita'} = users;

    result.innerText = `a: ${a} - b: ${b} - c: ${c} - d: ${d1}`;
});