end video

This lesson is only accessible in the paid version of the course.

Get access to all lessons 💫 price: 34.99$

If you already have an account click here.

§ What is destructuring in JavaScript and why is useful

Destructuring allows you to extract values from arrays or objects and assign them to variables in a concise syntax. In this lesson we are going to see it in action.

Destructuring is a feature in JavaScript that allows us to extract values from arrays or objects and assign them to variables. This can be helpful when we have a complex data structure and we want to extract specific values to work with.

For example, let's say we have an array of products

const products = [
  { name: 'Apple', price: 0.99, quantity: 10 },
  { name: 'Orange', price: 1.49, quantity: 20 },
  { name: 'Banana', price: 0.79, quantity: 15 }
];

and we want to extract the name and price of each product. Without destructuring, we might do this using a for loop and accessing each property individually:

for (let i = 0; i < products.length; i++) {
  const name = products[i].name;
  const price = products[i].price;
  console.log(`Product: ${name}, Price: ${price}`);
}

With destructuring, we can extract the values in a single line of code:

for (let { name, price } of products) {
  console.log(`Product: ${name}, Price: ${price}`);
}

We can also use destructuring with objects by using an object pattern. For example:

const product = {
  name: 'Apple',
  price: 0.99,
  quantity: 10
};

const { name, price } = product;
console.log(`Product: ${name}, Price: ${price}`);

Destructuring can make it easier to extract and work with specific values from complex data structures.

questionnaire

Practice

Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.

Practice
discussion

Materials

Materials related to the lesson:
Files associated with the lesson

Materials

Next: Scope(09:19)

To the lesson →