DEV Community

Lokesh
Lokesh

Posted on

Destructuring in JavaScript

1. What Is Destructuring?

Destructuring is a JavaScript feature that allows us to extract values from arrays and properties from objects and store them in separate variables.

It helps us write cleaner and shorter code.

2. Array Destructuring

Let's take a simple example.

const fruits = ["Apple", "Banana", "Mango"];

const [first, second, third] = fruits;

console.log(first);
console.log(second);
console.log(third);
Enter fullscreen mode Exit fullscreen mode

Output:

Apple
Banana
Mango
Enter fullscreen mode Exit fullscreen mode

Here, the values are assigned based on their positions in the array.

  • first gets Apple.
  • second gets Banana.
  • third gets Mango.

3. Skipping Array Elements

We can skip elements using commas.

const numbers = [10, 20, 30, 40];

const [first, , third] = numbers;

console.log(first);
console.log(third);
Enter fullscreen mode Exit fullscreen mode

Output:

10
30
Enter fullscreen mode Exit fullscreen mode

Here, we skipped the second element.

4. Default Values in Array Destructuring

We can assign default values if an array element is undefined.

const numbers = [10];

const [a, b = 20] = numbers;

console.log(a);
console.log(b);
Enter fullscreen mode Exit fullscreen mode

Output:

10
20
Enter fullscreen mode Exit fullscreen mode

Since the second element doesn't exist, the default value 20 is assigned.

5. Object Destructuring

We can also extract properties from objects.

const student = {
    name: "Lokesh",
    age: 22,
    course: "Java"
};

const { name, age, course } = student;

console.log(name);
console.log(age);
console.log(course);
Enter fullscreen mode Exit fullscreen mode

Output:

Lokesh
22
Java
Enter fullscreen mode Exit fullscreen mode

Unlike arrays, object destructuring uses property names instead of positions.

6. Renaming Variables

We can give different names to variables while destructuring objects.

const student = {
    name: "Lokesh",
    age: 22
};

const { name: studentName, age: studentAge } = student;

console.log(studentName);
console.log(studentAge);
Enter fullscreen mode Exit fullscreen mode

Output:

Lokesh
22
Enter fullscreen mode Exit fullscreen mode

Here, name is stored in studentName, and age is stored in studentAge.

7. Default Values in Object Destructuring

We can provide default values when an object property is missing or has the value undefined.

const student = {
    name: "Lokesh"
};

const { name, age = 21 } = student;

console.log(name);
console.log(age);
Enter fullscreen mode Exit fullscreen mode

Output:

Lokesh
21
Enter fullscreen mode Exit fullscreen mode

Since the age property is not available, the default value 21 is used.

Remember:

  • Array destructuring uses [].
  • Object destructuring uses {}.
  • Arrays use positions to extract values.
  • Objects use property names to extract values.
  • We can skip elements, rename variables, and assign default values.

Top comments (0)