JS Tutorial



JS DESTRUCTING


JavaScript Destructuring 🧩

Destructuring is a convenient way to extract values from arrays or properties from objects into separate variables.

📦 Array Destructuring

You can assign array values to variables in a single line:

const colors = ["red", "green", "blue"];
const [first, second, third] = colors;

console.log(first);  // "red"
console.log(second); // "green"

⚙️ Object Destructuring

Extract object properties easily into variables:

const person = { name: "Alice", age: 30 };
const { name, age } = person;

console.log(name); // "Alice"
console.log(age);  // 30

✨ Live Example: Object Destructuring

🎯 Destructuring with Default Values

If a value is undefined, you can set a default:

const [a = 1, b = 2] = [];
console.log(a); // 1
console.log(b); // 2

🔄 Swapping Variables with Destructuring

let x = 5, y = 10;
[x, y] = [y, x];
console.log(x); // 10
console.log(y); // 5

📂 Nested Destructuring

const user = {
  id: 101,
  profile: {
    name: "John",
    age: 25
  }
};

const { profile: { name, age } } = user;
console.log(name); // "John"
Tip: Destructuring makes your code cleaner and easier to read when working with complex data.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review