JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What is destructuring assignment in JavaScript?

Asked on Jul 15, 2024

Answer

Destructuring assignment in JavaScript is a convenient way to extract values from arrays or properties from objects into distinct variables. It simplifies the syntax and makes the code more readable.
<!-- BEGIN COPY / PASTE -->
        // Array destructuring
        const [first, second] = [10, 20];
        console.log(first); // 10
        console.log(second); // 20

        // Object destructuring
        const user = { name: "Alice", age: 25 };
        const { name, age } = user;
        console.log(name); // "Alice"
        console.log(age); // 25
        <!-- END COPY / PASTE -->
Additional Comment:
  • Destructuring allows you to unpack values from arrays or properties from objects into separate variables.
  • In array destructuring, the order of variables matters, while in object destructuring, the variable names must match the property names.
  • You can provide default values in case the unpacked value is undefined.
✅ Answered with JavaScript best practices.
← Back to All Questions