Destructuring is one of the most versatile expressions ever added to JavaScript. Why? Because it allows developers to write cleaner code in countless situations. Once you fully grasp destructing you’ll be shocked by how often it can be used. Let’s dive in!

The Basics

At it’s core, destructuring is an expression that makes it possible to extract values from arrays and objects and save them into variables. This expression emulates the syntax of the type it is destructuring

let [one, two, three] = [1, 2, 3];

console.log(one, two, three); // 1 2 3

let { numOne, numTwo, numThree } = {
  one: 1,
  two: 2,
  three: 3,
};

console.log(numOne, numTwo, numThree); // 1 2 3

While they look quite similar, there are key differences in how objects and array destructuring works. Array destructuring relies on the index of array elements to extract values.

let [three, two, one] = [1, 2, 3];

console.log(three); // 1

The variable three  has been set equal to the element located at the 0 index of the array. In our case, that element is 1 . The names assigned to variables when destructuring arrays do not determine which values will be extracted from the array.

#javascript #web-development #javascript-tips

Write Cleaner JavaScript with These Destructuring Techniques
27.85 GEEK