js destructuring explained

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:


        const arr = [1, 2, 3];
    

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


        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:


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

Destructuring Objects

Similarly, you can extract values from objects as well:


        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:


        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:


        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!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe