How to Destructure Object in Function Argument in Javascript

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

A property in the object is just a key-value pair. During the object destructuring, the name of the variable and the name of the key should be the same.  We can also extract properties from the nested objects as well as we can assign a default value to the variable if a property does not even exist.

Destructuring an object in the function argument is pretty much the same as we do it generally. I suggest you to have a look over MDN docs to get a basic idea about object destructuring.

In the following example, we will pass an object to a function as an argument.  We will destructure it, 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 are calling myFunction() and passing users object as an argument.
  • In myFunction(), we are destructuring the object and as a result, we have 3 variables a, b, and c. We are forming a template string using those 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: 'Peter',
        b: 'James',
        c: 'Ronald'
    };

    myFunction(users);
});

function myFunction({a, b, c}){
    result.innerText = `a: ${a} - b: ${b} - c: ${c}`
}