How to Make var [a, b] = {a: 1, b: 2} Work in JavaScript?
The article explains why the destructuring statement var [a, b] = {a: 1, b: 2} throws a TypeError, details the iterator requirement for the left‑hand side, and shows how to add a Symbol.iterator method to Object.prototype so any object becomes iterable and the assignment succeeds.
This is a ByteDance interview question that many candidates find puzzling at first glance. In JavaScript, the left side of a destructuring assignment must be an iterable (such as an array, Map, or Set). Attempting to destructure an object with array syntax, e.g., var [a, b] = {a: 1, b: 2}, results in a TypeError because plain objects lack an iterator.
The runtime error looks like:
var [a, b] = {a: 1, b: 2}
TypeError: {(intermediate value)(intermediate value)} is not iterableTo understand why, the article demonstrates that for...of can iterate over arrays but not over objects:
let arr = [1, 2, 3]
let obj = {a: 1, b: 2, c: 3}
for (let item of arr) { console.log(item) } // prints 1 2 3
for (let item of obj) { console.log(item) } // TypeError: obj is not iterableInspecting the array prototype reveals the presence of Symbol.iterator, a function that returns an iterator object:
console.log(arr.__proto__[Symbol.iterator]()); // Object[Array Iterator] {}The essential point is that any data structure possessing a [Symbol.iterator] property whose value is a function returning an iterator is considered iterable.
Armed with this knowledge, the solution is to give a plain object an iterator by augmenting Object.prototype:
Object.prototype[Symbol.iterator] = function () {
// Use Object.values(this) to get all values and return their iterator
return Object.values(this)[Symbol.iterator]();
};
var [a, b] = {a: 1, b: 2};
console.log(a, b); // 1 2After redefining Object.prototype[Symbol.iterator], the object becomes iterable, and the destructuring assignment succeeds without error.
The article concludes by encouraging readers that they have now mastered this tricky interview question and can confidently handle similar scenarios in future interviews.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IoT Full-Stack Technology
Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
