पाठ 19 / 38
ऐरे और ऑब्जेक्ट Destructuring
एक पंक्ति में array और ऑब्जेक्ट से मान निकालें।
ऐरे destructuring
यहाँ स्थिति मायने रखती है — खाली slot से आइटम छोड़ सकते हैं, और एक पंक्ति में वेरिएबल स्वैप भी कर सकते हैं।
const [first, second, , fourth] = [10, 20, 30, 40];
console.log(first, second, fourth); // 10 20 40
let [a, b] = [1, 2];
[a, b] = [b, a]; // swap
console.log(a, b); // 2 1ऑब्जेक्ट destructuring
यहाँ नाम मायने रखते हैं, क्रम नहीं — और गुम keys के लिए डिफ़ॉल्ट भी सेट कर सकते हैं।
const { name, age } = { name: "Ada", age: 36 };
console.log(name, age);
const { city = "Unknown" } = {};
console.log(city); // UnknownDestructuring में नाम बदलना
const { name: fullName } = user; से name को fullName नाम के वेरिएबल में निकाला जाता है।
त्वरित जाँच: `const [a, , b] = [1, 2, 3]` में b का मान क्या होगा?
- 2
- 3
- undefined
Answer
3 — खाली slot इंडेक्स 1 को छोड़ देता है, इसलिए b इंडेक्स 2 उठाता है, जिसमें 3 है।