What is destructuring assignment ?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

- From MDN

Advantages

  • Makes code concise and more readable.

  • We can easily avoid repeated destructing expression.

Some use cases

  1. To get values in variable from Objects, array

    let obj = { 'a': 1,'b': {'b1': '1.1'}}
    let {a,b,b:{b1}} = obj
    console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1)
    
    let obj2 = { foo: 'foo' };
    let { foo: newVarName } = obj2;
    console.log(newVarName);
    
    let arr = [1, 2, 3, 4, 5]
    let [first, second, ...rest] = arr
    console.log(first, '\n', second, '\n', rest)
    
    
    // Nested extraction is possible too:
    let obj3 = { foo: { bar: 'bar' } };
    let { foo: { bar } } = obj3;
    console.log(bar);

  2. To change only desired property in an object

    let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}]
    
    let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10}))
    
    console.log(op)

  3. To extract values from parameters into standalone variables

    // Object destructuring:
    const fn = ({ prop }) => {
      console.log(prop);
    };
    fn({ prop: 'foo' });
    
    
    console.log('------------------');
    
    
    // Array destructuring:
    const fn2 = ([item1, item2]) => {
      console.log(item1);
      console.log(item2);
    };
    fn2(['bar', 'baz']);
    
    
    console.log('------------------');
    
    
    // Assigning default values to destructured properties:
    
    const fn3 = ({ foo="defaultFooVal", bar }) => {
      console.log(foo, bar);
    };
    fn3({ bar: 'bar' });

  4. To get dynamic keys value from object

    let obj = {a:1,b:2,c:3}
    let key = 'c'
    let {[key]:value} = obj
    
    console.log(value)

  5. To swap values

    const b = [1, 2, 3, 4];
    [b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2
    
    console.log(b);

  6. To get a subset of an object

    • subset of an object:

      const obj = {a:1, b:2, c:3},
            subset = (({a, c}) => ({a, c}))(obj); // credit to Ivan N for this function
      
      console.log(subset);

    • To get a subset of an object using comma operator and destructuring:

      const object = { a: 5, b: 6, c: 7  };
      const picked = ({a,c}=object, {a,c})
      
      console.log(picked); // { a: 5, c: 7 }

  7. To do array to object conversion:

    const arr = ["2019", "09", "02"],
          date = (([year, day, month]) => ({year, month, day}))(arr);
    
    console.log(date);

  8. To set default values in function. (Read this answer for more info )

    function someName(element, input, settings={i:"#1d252c", i2:"#fff", ...input}){
        console.log(settings.i);
        console.log(settings.i2);
    }
    
    someName('hello', {i: '#123'});
    someName('hello', {i2: '#123'});

  9. To get properties such as length from an array, function name, number of arguments etc.

    let arr = [1,2,3,4,5];
    
    let {length} = arr;
    
    console.log(length);
    
    let func = function dummyFunc(a,b,c) {
      return 'A B and C';
    }
    
    let {name, length:funcLen} = func;
    
    console.log(name, funcLen);

🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
Destructuring assignment
February 26, 2026 - The function might only require certain elements or properties. Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › destructuring-assignment-in-javascript
Destructuring in JavaScript - GeeksforGeeks
Destructuring Assignment is a JavaScript expression that allows to unpack of values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, and nested objects, and assigned to variables.
Published   November 9, 2024
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Destructuring
Destructuring - JavaScript - MDN Web Docs
The destructuring syntax is a JavaScript syntax that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. It can be used in locations that receive data (such as the left-hand side of an assignment or anywhere that creates new identifier bindings).
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Destructuring_assignment
Destructuring - JavaScript | MDN
The destructuring syntax is a JavaScript syntax that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. It can be used in locations that receive data (such as the left-hand side of an assignment or anywhere that creates new identifier bindings).
🌐
W3Schools
w3schools.com › JS › js_destructuring.asp
JavaScript Destructuring
JS Examples JS HTML DOM JS HTML ... Certificate · ❮ Previous Next ❯ · The destructuring assignment syntax can unpack objects into variables: let {firstName, lastName} = person; // Create an Object const person = { firstName: ...
🌐
Medium
teapuddles.medium.com › daily-uses-for-destructuring-assignment-in-javascript-44683b92157e
Daily Uses for Destructuring Assignment in Javascript | by Kevin Gleeson | Medium
October 23, 2020 - According to MDN, the definition of destructuring assignment is that it’s syntax in a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › es6 destructuring assignment
ES6 Destructuring Assignment - JavaScript Tutorial
November 8, 2024 - ES6 introduces a new feature called destructuring assignment, which lets you destructure properties of an object or elements of an array into individual variables.
🌐
MDN Web Docs
devdoc.net › web › developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Destructuring_assignment.html
Destructuring assignment - JavaScript | MDN
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Find elsewhere
🌐
Medium
medium.com › @ayoub-mabrouk › understanding-the-javascript-destructuring-assignment-798d7c959132
Understanding the JavaScript destructuring assignment | by Ayoub Mabrouk | Medium
August 8, 2022 - The object destructuring assignment ... most in ReactJs, VueJs, and Angular that enables us to easily extract multiple data from arrays, objects and assign that data to any variables, It also allows us to specify a default value ...
Top answer
1 of 3
37

What is destructuring assignment ?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

- From MDN

Advantages

  • Makes code concise and more readable.

  • We can easily avoid repeated destructing expression.

Some use cases

  1. To get values in variable from Objects, array

    let obj = { 'a': 1,'b': {'b1': '1.1'}}
    let {a,b,b:{b1}} = obj
    console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1)
    
    let obj2 = { foo: 'foo' };
    let { foo: newVarName } = obj2;
    console.log(newVarName);
    
    let arr = [1, 2, 3, 4, 5]
    let [first, second, ...rest] = arr
    console.log(first, '\n', second, '\n', rest)
    
    
    // Nested extraction is possible too:
    let obj3 = { foo: { bar: 'bar' } };
    let { foo: { bar } } = obj3;
    console.log(bar);

  2. To change only desired property in an object

    let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}]
    
    let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10}))
    
    console.log(op)

  3. To extract values from parameters into standalone variables

    // Object destructuring:
    const fn = ({ prop }) => {
      console.log(prop);
    };
    fn({ prop: 'foo' });
    
    
    console.log('------------------');
    
    
    // Array destructuring:
    const fn2 = ([item1, item2]) => {
      console.log(item1);
      console.log(item2);
    };
    fn2(['bar', 'baz']);
    
    
    console.log('------------------');
    
    
    // Assigning default values to destructured properties:
    
    const fn3 = ({ foo="defaultFooVal", bar }) => {
      console.log(foo, bar);
    };
    fn3({ bar: 'bar' });

  4. To get dynamic keys value from object

    let obj = {a:1,b:2,c:3}
    let key = 'c'
    let {[key]:value} = obj
    
    console.log(value)

  5. To swap values

    const b = [1, 2, 3, 4];
    [b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2
    
    console.log(b);

  6. To get a subset of an object

    • subset of an object:

      const obj = {a:1, b:2, c:3},
            subset = (({a, c}) => ({a, c}))(obj); // credit to Ivan N for this function
      
      console.log(subset);

    • To get a subset of an object using comma operator and destructuring:

      const object = { a: 5, b: 6, c: 7  };
      const picked = ({a,c}=object, {a,c})
      
      console.log(picked); // { a: 5, c: 7 }

  7. To do array to object conversion:

    const arr = ["2019", "09", "02"],
          date = (([year, day, month]) => ({year, month, day}))(arr);
    
    console.log(date);

  8. To set default values in function. (Read this answer for more info )

    function someName(element, input, settings={i:"#1d252c", i2:"#fff", ...input}){
        console.log(settings.i);
        console.log(settings.i2);
    }
    
    someName('hello', {i: '#123'});
    someName('hello', {i2: '#123'});

  9. To get properties such as length from an array, function name, number of arguments etc.

    let arr = [1,2,3,4,5];
    
    let {length} = arr;
    
    console.log(length);
    
    let func = function dummyFunc(a,b,c) {
      return 'A B and C';
    }
    
    let {name, length:funcLen} = func;
    
    console.log(name, funcLen);

2 of 3
3

It is something like what you have can be extracted with the same variable name

The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment

var [one, two, three] = ['orange', 'mango', 'banana'];

console.log(one); // "orange"
console.log(two); // "mango"
console.log(three); // "banana"

and you can get user properties of an object using destructuring assignment,

var {name, age} = {name: 'John', age: 32};

console.log(name); // John
console.log(age); // 32
🌐
Programiz
programiz.com › javascript › destructuring-assignment
JavaScript Destructuring Assignment
The destructuring assignment introduced in ES6 makes it easy to assign array values and object properties to distinct variables.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-destructuring-assignment-in-javascript
How To Use Destructuring Assignment In JavaScript | DigitalOcean
December 12, 2019 - When destructuring objects, we use the keys as variable names. This is how JavaScript knows which property of the object you want to assign. Unlike arrays where you use their index/positions in the assignment, here you use the keys.
🌐
Educative
educative.io › answers › what-is-a-destructuring-assignment-in-javascript
What is a destructuring assignment in JavaScript?
In destructuring, the left-hand side of the assignment operator contains variable(s) that will store the destructured values.
🌐
OpenReplay
blog.openreplay.com › openreplay blog › the javascript destructuring assignment explained
The JavaScript Destructuring Assignment Explained
July 25, 2024 - JavaScript destructuring assignment gives you a quick way to pull values from arrays or grab properties from objects and put them into separate variables. Before ES6 showed up, coders had to write long, repetitive code to get stuff out of arrays ...
🌐
Medium
medium.com › getpowerplay › destructuring-assignment-in-javascript-part-1-98537a644964
Destructuring assignment in JavaScript | by Nirmal Jasmatiya | Powerplay | Medium
March 2, 2022 - Destructuring assignment syntax (Introduced in ES6) is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables.
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_destructuring_assignment.htm
JavaScript - Destructuring Assignment
In JavaScript, the destructuring assignment is an expression that allows us to unpack the values from the arrays or objects and store them in individual variables.
🌐
freeCodeCamp
freecodecamp.org › news › array-vs-object-destructuring-in-javascript
Array vs Object Destructuring in JavaScript – What’s the Difference?
November 10, 2021 - The destructuring assignment in JavaScript provides a neat and DRY way to extract values from your arrays and objects. This article aims to show you exactly how array and object destructuring assignments work in JavaScript.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › destructuring assignment introduction
Where and how can I use the destructuring assignment syntax in JavaScript? - 30 seconds of code
June 12, 2021 - The destructuring assignment syntax, first introduced in JavaScript ES6, allows the unpacking of values from arrays and objects into distinct variables. While it might seem intimidating at first, it's actually quite easy to learn and use.
🌐
Wayback Machine
web.archive.org › web › 20160304055633 › https: › developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Destructuring_assignment
Destructuring assignment - JavaScript | MDN
The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals. var a, b; [a, b] = [1, 2] [a, b, ...rest] ...