JavaScript Destructuring in Loops

In this section, we will learn what the destructuring in loops is and how to use it in JavaScript.

What is JavaScript Destructuring in Loops?

In JavaScript, there are some assignments that don’t really look like assignments! In particular, the `for-in` and `for-of` loops assign values to the loop-variable at the beginning of each iteration. We can use destructuring there, as well. There are not much use cases to use destructuring in `for-in` loop especially because the keys a `for-in` loop provides are always strings, and it’s rare we want to destructure a string-although we can, since strings are iterable, but it can be very handy when using `for-of` loop.

Example: using destructuring in for of loop

const list = [
  {firstName: "John", lastName:"Doe"},
  {firstName: "Omid", lastName:"Dehghan"},
  {firstName: "Jack", lastName: "Bauer"}
]
for (const {firstName, lastName} of list){
  console.log(`The first name is: ${firstName} and the last name is: ${lastName}`);
}

Output:

The first name is: John and the last name is: Doe

The first name is: Omid and the last name is: Dehghan

The first name is: Jack and the last name is: Bauer

How Does Destructuring in for of Statement Work?

Each element in the `list` is an object that has two properties, named `firstName` and `lastName`.

So in the `for-of` loop, we’ve created a destructuring pattern that takes each element (object) of the `list` and assign the values of the `firstName` and `lastName` properties into the two identifiers with the same name in this loop.

Reference book:

JavaScript the New Toys

Author: T.J. Crowder

Leave a Reply