HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Destructuring

Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. It makes your code much cleaner and easier to read.


1. Object Destructuring

You can extract properties from an object directly into variables with the same name.

const person = { name: "Mim", age: 22, city: "Dhaka" };

// Destructuring
const { name, age } = person;

console.log(name); // Mim
console.log(age);  // 22

Using Aliases

You can also rename the variables during destructuring:

const { name: fullName, age: yearsOld } = person;
console.log(fullName); // Mim

2. Array Destructuring

When destructuring arrays, the order is important. Values are assigned based on their position (index).

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

// Unpacking values
const [first, second] = fruits;

console.log(first);  // Apple
console.log(second); // Banana

Default Values

A variable can be assigned a default value, in the case that the value unpacked from the object or array is undefined.

const person = { name: " Mim" };
const { name, country = "Bangladesh" } = person;

console.log(country); // Bangladesh

Practical Use: Function Parameters

Destructuring is extremely useful for handling object parameters in functions, making the required data very explicit.

function printUser({ name, age }) {
  console.log(`${name} is ${age} years old.`);
}

const user = { name: "Mim", age: 22, color: "Blue" };
printUser(user);

Key Points to Remember

  • Destructuring creates new variables matching data from objects/arrays
  • In Objects, variables must match the property name (or use an alias)
  • In Arrays, order determines the assignment
  • Default values prevent undefined results
  • Great for simplifying complex API responses
  • Works with nested data structures too