📘 Lesson · Lesson 40
Destructuring and Spread
Destructuring और Spread
What Destructuring Is
const student = { name: "Aman", marks: 85, city: "Aligarh" };
// The long way:
const name = student.name;
const marks = student.marks;
// Destructuring — pull them out in one line:
const { name, marks } = student;
console.log(name, marks); // "Aman" 85
Destructuring unpacks values from arrays or properties from objects into separate variables, in a single readable line. It removes the repetitive
const x = obj.x pattern that used to fill the top of every function. It's purely a convenience — the same result, far less typing — but it's used so heavily in modern JavaScript (and in React) that you'll see it in almost every codebase. The syntax mirrors the structure of the data you're pulling from, which is why it's called destructuring.Array Destructuring — by position
const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first); // "red" ← by POSITION
console.log(second); // "green"
const [a, , c] = colors; // skip an item with an empty slot
console.log(c); // "blue"
const [head, ...rest] = colors; // rest = ["green", "blue"]
// The neat swap trick:
let x = 1, y = 2;
[x, y] = [y, x]; // x is now 2, y is 1 — no temp variable!
Array destructuring pulls items out by POSITION, using square brackets on the left of the
=. The first variable gets index 0, the second index 1, and so on. Leave a blank slot (just a comma) to skip an item, and use ...rest to collect everything remaining into a new array. The most beloved trick is swapping two variables in one line: [x, y] = [y, x], no temporary variable required. Since positions matter here, the variable NAMES are entirely up to you.Object Destructuring — by property name
const student = { name: "Aman", marks: 85, city: "Aligarh" };
const { name, city } = student; // order doesn't matter — names do
console.log(name, city); // "Aman" "Aligarh"
const { missing } = student; // undefined — no error
// Nested objects:
const user = { name: "Aman", address: { city: "Aligarh" } };
const { address: { city } } = user;
console.log(city); // "Aligarh"
Object destructuring uses curly braces, and matches by PROPERTY NAME rather than position — so the order you list them in is irrelevant, but the names must match the object's keys exactly. Ask for a key that doesn't exist and you simply get
undefined, no error. You can also reach into nested objects by mirroring their shape, though deep nesting gets hard to read quickly. Key contrast: arrays destructure by position, objects by name.Renaming and Default Values
const student = { name: "Aman", marks: 85 };
// Rename while destructuring (: newName)
const { name: studentName } = student;
console.log(studentName); // "Aman"
// Default value if the property is missing (= value)
const { city = "Unknown" } = student;
console.log(city); // "Unknown"
// Both together:
const { city: town = "Unknown" } = student; // town = "Unknown"
Two useful extras. Use a colon to RENAME a variable as you extract it — handy when the property name clashes with an existing variable, or is unclear. Use
= to supply a DEFAULT value for properties that might not exist, exactly like default function parameters. The default only applies when the value is undefined. Combining them reads as { originalKey: newName = defaultValue } — a compact and very common pattern when handling API data with optional fields.Destructuring Function Parameters — very common
// Instead of accessing properties inside:
function showStudent(student) {
console.log(student.name, student.marks);
}
// Destructure right in the parameter list:
function showStudent({ name, marks }) {
console.log(name, marks);
}
showStudent({ name: "Aman", marks: 85 });
// Especially clean with array methods:
const students = [{ name: "Aman", marks: 85 }, { name: "Priya", marks: 92 }];
students.forEach(({ name, marks }) => console.log(`${name}: ${marks}`));
const [first] = students.filter(s => s.marks > 90); // array destructuring too
Destructuring directly in the parameter list is where it truly shines. Rather than passing three positional arguments (and worrying about their order, as the parameters chapter warned), you pass ONE object and destructure the fields you need — self-documenting, order-independent, and easy to extend. It's also beautiful with array methods:
forEach(({ name }) => ...) pulls just the field you want from each object. This combination of arrays of objects, array methods, and destructuring is the everyday texture of modern JavaScript.Exam Corner
Q: How does array destructuring match values? By position; object destructuring matches by property name.
Q: Swap two variables using destructuring.
Q: How do you rename a variable while destructuring an object?
Q: How do you give a destructured property a default?
Q: Why destructure function parameters? Order no longer matters, the code self-documents, and it's easy to add fields.
Q: Swap two variables using destructuring.
[x, y] = [y, x]Q: How do you rename a variable while destructuring an object?
const { name: newName } = objQ: How do you give a destructured property a default?
const { city = "Unknown" } = objQ: Why destructure function parameters? Order no longer matters, the code self-documents, and it's easy to add fields.
Destructuring क्या है
const student = { name: "Aman", marks: 85, city: "Aligarh" };
// Lamba tarika:
const name = student.name;
const marks = student.marks;
// Destructuring — ek line me nikalo:
const { name, marks } = student;
console.log(name, marks); // "Aman" 85
Destructuring arrays से values या objects से properties को अलग variables में एक पढ़ने योग्य line में खोलता है. यह दोहराने वाला
const x = obj.x pattern हटाता है जो हर function के ऊपर भरा रहता था. यह पूरी तरह सुविधा है — वही नतीजा, कहीं कम typing — पर modern JavaScript (और React) में इतना ज़्यादा use होता है कि आप इसे लगभग हर codebase में देखेंगे. Syntax उस data की structure दर्शाता है जिससे आप खींच रहे हैं, इसीलिए इसे destructuring कहते हैं.Array Destructuring — position से
const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first); // "red" ← POSITION se
console.log(second); // "green"
const [a, , c] = colors; // khali slot se item skip karo
console.log(c); // "blue"
const [head, ...rest] = colors; // rest = ["green", "blue"]
// Saaf swap trick:
let x = 1, y = 2;
[x, y] = [y, x]; // x ab 2, y ab 1 — koi temp variable nahi!
Array destructuring items को POSITION से निकालता है,
= के बाईं ओर square brackets से. पहला variable index 0 पाता है, दूसरा index 1, वगैरह. Item skip करने को खाली slot (बस comma) छोड़िए, और बचा सब नई array में इकट्ठा करने को ...rest use कीजिए. सबसे प्रिय trick है एक line में दो variables swap करना: [x, y] = [y, x], कोई temporary variable नहीं चाहिए. चूंकि यहां positions मायने रखती हैं, variable NAAM पूरी तरह आपकी मर्ज़ी.Object Destructuring — property नाम से
const student = { name: "Aman", marks: 85, city: "Aligarh" };
const { name, city } = student; // order mayne nahi rakhta — naam rakhte hain
console.log(name, city); // "Aman" "Aligarh"
const { missing } = student; // undefined — koi error nahi
// Nested objects:
const user = { name: "Aman", address: { city: "Aligarh" } };
const { address: { city } } = user;
console.log(city); // "Aligarh"
Object destructuring curly braces use करता है, और position के बजाय PROPERTY NAAM से match करता है — तो आप उन्हें किस order में लिखते हैं अप्रासंगिक है, पर नाम object की keys से ठीक match होने चाहिए. न मौजूद key मांगिए और आपको बस
undefined मिलता है, कोई error नहीं. आप nested objects में भी उनकी shape दर्शाकर पहुंच सकते हैं, हालांकि गहरा nesting जल्दी पढ़ने में मुश्किल हो जाता है. मुख्य विरोधाभास: arrays position से destructure, objects नाम से.Renaming और Default Values
const student = { name: "Aman", marks: 85 };
// Destructure karte samay rename (: newName)
const { name: studentName } = student;
console.log(studentName); // "Aman"
// Property gayab ho to default value (= value)
const { city = "Unknown" } = student;
console.log(city); // "Unknown"
// Dono saath:
const { city: town = "Unknown" } = student; // town = "Unknown"
दो उपयोगी अतिरिक्त. निकालते समय variable RENAME करने को colon use कीजिए — काम का जब property नाम मौजूदा variable से टकराए, या अस्पष्ट हो. न मौजूद properties के लिए DEFAULT value देने को
= use कीजिए, ठीक default function parameters जैसे. Default सिर्फ तब लगता है जब value undefined हो. दोनों मिलाकर { originalKey: newName = defaultValue } पढ़ता है — optional fields वाले API data संभालते समय संक्षिप्त और बहुत common pattern.Function Parameters Destructure करना — बहुत common
// Andar properties access karne ke bajaye:
function showStudent(student) {
console.log(student.name, student.marks);
}
// Parameter list me hi destructure:
function showStudent({ name, marks }) {
console.log(name, marks);
}
showStudent({ name: "Aman", marks: 85 });
// Array methods ke saath khaaskar saaf:
const students = [{ name: "Aman", marks: 85 }, { name: "Priya", marks: 92 }];
students.forEach(({ name, marks }) => console.log(`${name}: ${marks}`));
const [first] = students.filter(s => s.marks > 90); // array destructuring bhi
Parameter list में सीधे destructuring वहीं है जहां यह सच में चमकता है. तीन positional arguments भेजने (और उनके order की चिंता करने, जैसा parameters chapter ने चेताया) के बजाय, आप EK object भेजते हैं और जो fields चाहिए destructure करते हैं — self-documenting, order-स्वतंत्र, और बढ़ाने में आसान. यह array methods के साथ भी सुंदर है:
forEach(({ name }) => ...) हर object से बस वही field खींचता है जो आप चाहते हैं. Objects की arrays, array methods, और destructuring का यह combination modern JavaScript का रोज़ का ताना-बाना है.Exam Corner
Q: Array destructuring values कैसे match करता है? Position से; object destructuring property नाम से match करता है.
Q: Destructuring से दो variables swap कीजिए.
Q: Object destructure करते समय variable rename कैसे करते हैं?
Q: Destructured property को default कैसे देते हैं?
Q: Function parameters destructure क्यों करें? Order मायने नहीं रखता, code self-document करता है, और fields जोड़ना आसान है.
Q: Destructuring से दो variables swap कीजिए.
[x, y] = [y, x]Q: Object destructure करते समय variable rename कैसे करते हैं?
const { name: newName } = objQ: Destructured property को default कैसे देते हैं?
const { city = "Unknown" } = objQ: Function parameters destructure क्यों करें? Order मायने नहीं रखता, code self-document करता है, और fields जोड़ना आसान है.
💻 Live Code Editor
इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का
console.log देखने के लिए F12 दबाइए.