How to Make var [a, b] = {a:1, b:2} Work in JavaScript?
This article explains why the destructuring statement var [a, b] = {a:1, b:2} throws a TypeError, explores the iterator protocol and Symbol.iterator, and shows how redefining Object.prototype[Symbol.iterator] enables the object to be iterable so the destructuring succeeds.
In JavaScript, destructuring on the left side expects an iterable, such as an array, while the right side must provide an object that implements the iterator protocol. Directly writing var [a, b] = {a: 1, b: 2} triggers a TypeError: ... is not iterable because plain objects lack a Symbol.iterator property.
The article first demonstrates the error by executing the statement and shows the console output. It then contrasts for...of on an array, which prints 1 2 3, with for...of on an object, which throws TypeError: obj is not iterable. By inspecting Array.prototype[Symbol.iterator], the author reveals that the iterator method returns an iterator object.
From this observation, the author defines an iterable as any data structure whose prototype contains a [Symbol.iterator] property whose value is a function returning an iterator. To satisfy the interview requirement, the object must be made iterable.
The solution adds an iterator to 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);After redefining the method, the previous error changes to
TypeError: Result of the Symbol.iterator method is not an objectbecause the function must return an iterator object, not just an array. By returning Object.values(this)[Symbol.iterator](), the function yields a proper iterator, and the destructuring succeeds, printing 1 2.
The article includes an illustration of Array.prototype[Symbol.iterator] and shows that the new Object.prototype[Symbol.iterator] works for any object, enabling for...of loops or destructuring on plain objects.
Finally, the author congratulates the reader for solving the ByteDance interview question and encourages confidence in similar scenarios.
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.
