Introduced in ECMAScript 2015 (ES6), Destructuring Assignment is one of the most expressive and time-saving syntax features in modern JavaScript. It allows developers to extract multiple pieces of data from arrays or objects and assign them to independent variables in a single clean statement.
const rgbColors = [255, 128, 0];
// Basic Array Unpacking by position:
const [red, green, blue] = rgbColors;
console.log(red); // 255
console.log(green); // 128
// Skipping Elements & Default Fallback Values:
const [primaryColor, , accentColor = "black"] = ["red", "green"];
console.log(primaryColor); // "red"
console.log(accentColor); // "black" (Used fallback!)
// Swapping variables in ONE line without temp variable!
let a = 10, b = 20;
[a, b] = [b, a];
console.log(`a = ${a}, b = ${b}`); // a = 20, b = 10
Unlike arrays (which unpack by position), objects unpack by property name:
const userProfile = {
userId: 1042,
username: "vikram99",
email: "vikram@example.com"
};
// 1. Basic Object Destructuring
const { username, email } = userProfile;
console.log(username); // "vikram99"
// 2. Renaming (Aliasing) & Default Values
const { userId: id, role = "Student" } = userProfile;
console.log(id); // 1042 (Stored in variable named 'id')
console.log(role); // "Student" (Default fallback)
// Clean parameter unpacking:
function displayStudentCard({ name, branch, gpa = 3.0 }) {
console.log(`Student: ${name} | Branch: ${branch} | GPA: ${gpa}`);
}
const studentRecord = { name: "Pooja Sharma", branch: "BCA", gpa: 3.8 };
displayStudentCard(studentRecord);
Exam Question: "Demonstrate nested object destructuring with a concrete code snippet."
const employee = {
empId: 501,
department: { deptName: "Engineering", floor: 3 }
};
const { empId, department: { deptName, floor } } = employee;
console.log(`ID: ${empId}, Dept: ${deptName}, Floor: ${floor}`);
// Output: ID: 501, Dept: Engineering, Floor: 3
What are the three dots (...) and how do they combine cloning, merging, and function arguments? Proceed to: JavaScript Spread & Rest Operators (...) →