Understanding JavaScript Destructuring Assignment

hyundonny·2021년 2월 23일
0

JavaScript Fundamentals

목록 보기
7/7
post-thumbnail

The destructuring assignment allows us to extract values from arrays and objects, even nested ones, in a short and concise format. The basics are more or less straightforward, but there were other parts weren't as intuitive. The following is a list of things that I will probably forget if I don't come back and look over again.

Destructuring !== Modification

The destructuring assignment does not modify the original object or array.

Use parentheses when destructuring object to a variable that's already been declared

let one, two, three;
const numObj = {
  one: 1,
  two: 2,
  three: 3
};

{one, two, three}  = numObj;
// Uncaught SyntaxError: Unexpected token '='


({one, two, three} = numObj;)
// one = 1, two = 2, three = 3

When we try to destructure the numObj without parentheses, JavaScript will consider the left side of the assignment to be a code block. As you can't assgin a value to a code block, it will result in a SyntaxErrror. We can avoid such errors by either declaring the variables at the time of destructuring or wrapping the entire expression in parentheses.

Don't forget the identifier when extracting a dynamic name property from objects.

Basic syntax:

const { [propName]: identifier } = expression;
// This is equal to
// const identifier = expression[propName];

Example:

let prop = "lastName";
const playerObj = {
  firstName: "Heung Min",
  lastName: "Son",
  clubs: ["Hamburg", "Leverkusen", "Tottenham"],
};

const {[prop]: surname} = playerObj;
surname; // 'Son'

Leaving out 'surname' will return a SyntaxError. Writing 'prop' instead of '[prop]' will look for a property with 'prop' as its value so look out for that too.

Destructuring nested objects

Basic syntax:

const { nestedObjectProp: { identifier } } = expression;
// This is equal to
// const identifier = expression.nestedObjectProp.identifier;

Destructuring multi-level nested objects

const { propA: { propB: { propC: { .... } } } } = object;
// What a nightmare. Oh well.

Example:

const player = {
  name: "Leo Messi",
  clubs: {
    Barcelona: {
      location: "Barcelona, Spain",
      stadium: {
        name: "Camp Nou",
        seatingCapacity: 99354,
      },
    },
  },
};

const {name: playerName} = player;
const {clubs: {Barcelona: {stadium: {name: stadiumName}}}} = player;
const {clubs: {Barcelona: {stadium: {seatingCapacity: seating}}}} = player;
playername; // 'Leo Messi'
stadiumName; // 'Camp Nou'
seating; // 99354

Interesting use cases

for ... of with destructuring assignment

const players = [
  { name: "Eric Abidal", club: "FC Barcelona" },
  { name: "Carles Puyol", club: "FC Barcelona" },
];
for ({ name: n, club: c } of players) {
  console.log(`${n}, ${c}`);
}

// "Eric Abidal, FC Barcelona"
// "Carles Puyol, FC Barcelona"

Rest syntax with destructuring assignment

let first, second, third;
({ first: gold, second: silver, third: bronze, ...others } = {
  first: "Tim",
  second: "Jim",
  third: "Kim",
  fourth: "Lim",
  fifth: "Pim",
});
gold; // "Tim"
silver; // "Jim"
bronze; // "Kim"
others; // {fourth: "Lim", fifth: "Pim"}

_Function parameter destructuring
_

const leoMessi = {
  name: "Leo Messi",
  goals: {
    club: 655,
    country: 71,
  },
};

function playerGoals({
  name,
  goals: { club: clubGoals },
  goals: { country: countryGoals },
}) {
  console.log(
    `${name} scored ${clubGoals} goals for his club and ${countryGoals} goals for his country`
  );
}

playerGoals(leoMessi);
// Leo Messi scored 655 goals for his club and 71 goals for his country

Works Cited

Destructuring assignment | Web technology for developers. (n.d.). Retrieved February 23, 2021, from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Pavlutin, D. (2020, May 26). How to use object destructuring in JavaScript. Retrieved February 23, 2021, from https://dmitripavlutin.com/javascript-object-destructuring/#1-the-need-for-object-destructuring

profile
Stumbling through, one step at a time

0개의 댓글