JavaScript - Destructuring

What is Destructuring?

In JavaScript, destructuring is a way to extract values from arrays or objects into distinct variables. It is a convenient way to unpack values from arrays or objects into a set of variables in a single line of code.

const numbers = [1, 2, 3];
const [a, b, c] = numbers;

console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3

In this example, the values of the numbers array are unpacked into the variables a, b, and c.

destructuring to ignore certain values by using a comma to skip them:

const numbers = [1, 2, 3, 4, 5];
const [a, , c, , e] = numbers;

console.log(a); // Output: 1
console.log(c); // Output: 3
console.log(e); // Output: 5

In this example, the values at indexes 1 and 3 are skipped and not assigned to any variables. using comma (,) you can skip the values in destructuring.

destructuring to unpack values from an object:

const person = {
  name: 'John',
  age: 30,
  job: 'software engineer'
};

const { name, age, job } = person;

console.log(name); // Output: 'John'
console.log(age); // Output: 30
console.log(job); // Output: 'software engineer'

In this example, the values of the name, age, and job properties of the person object are unpacked into the variables with the same names.

destructuring to assign the values to variables with different names:

const person = {
  name: 'John',
  age: 30,
  job: 'software engineer'
};

const { name: n, age: a, job: j } = person;

console.log(n); // Output: 'John'
console.log(a); // Output: 30
console.log(j); // Output: 'software engineer'

n this example, the values of the name, age, and job properties of the person object are unpacked into the variables n, a, and j, respectively.