Skip to content
the poor coder

js destructuring explained

Poor Man
Published
Reading time
2 min read
On this page

JavaScript Destructuring Explained#

If you are a JavaScript developer, you may have heard of the term "Destructuring". Destructuring is a feature introduced in ES6 that allows you to extract elements from arrays or objects and assign them to variables. In simple terms, it provides a shorthand syntax to extract multiple values from an array or object and assign them to variables.

Destructuring Arrays#

Let's say you have an array containing three elements:

Text

        const arr = [1, 2, 3];
    

You can extract each element and assign them to variables using destructuring as follows:

Text

        const [a, b, c] = arr;
        console.log(a); // 1
        console.log(b); // 2
        console.log(c); // 3
    

You can also skip elements by leaving an empty space in the destructuring syntax:

Text

        const [a, , c] = arr;
        console.log(a); // 1
        console.log(c); // 3
    

Destructuring Objects#

Similarly, you can extract values from objects as well:

Text

        const obj = {name: "John", age: 30};
        const {name, age} = obj;
        console.log(name); // John
        console.log(age); // 30
    

You can also assign a new variable name to the extracted values:

Text

        const obj = {name: "John", age: 30};
        const {name: myName, age: myAge} = obj;
        console.log(myName); // John
        console.log(myAge); // 30
    

Destructuring Function Parameters#

Destructuring can also be used with function parameters:

Text

        function getUser({name, age}) {
            console.log(name);
            console.log(age);
        }
        
        getUser({name: "John", age: 30});
    

The above code will log "John" and 30 to the console.

Conclusion#

In conclusion, destructuring is a powerful feature in JavaScript that simplifies your code and makes it more readable. It can be used with arrays, objects, and function parameters to extract values and assign them to variables. Use destructuring to write cleaner and more efficient code!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC