Symbol.iterator — JS Technical Interview Questions & Answers
The well-known symbol that makes a value iterable.
Symbol.iterator
- Symbol.iterator is a JS topic. In plain words you use it for a short Symbol.iterator example in a script in the browser. Don’t start with a slogan — start with that picture.
- Smallest example: the smallest Symbol.iterator example you can type. Type it, run it, and say what you see. If you can do that from memory, you know Symbol.iterator.
- From the example next to this theory: The well-known symbol that makes a value iterable.
- Trap: only saying “Symbol.iterator” with no example. Fix that before you talk about advanced JS.
- Viva: what is Symbol.iterator? Then show the smallest Symbol.iterator example you can type. Then name the trap.
Technical Interview Tip: What is Symbol.iterator? Show this: the smallest Symbol.iterator example you can type. Trap: only saying “Symbol.iterator” with no example.
Code Examples for Symbol.iterator
Symbol.iterator — working example
const nums = [10, 20];
console.log(...nums);
const range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let n = this.from;
const last = this.to;
return {
next() {
if (n <= last) return { value: n++, done: false };
return { done: true };
},
};
},
};
console.log([...range]);Symbol.iterator — for...of and spread use the iterable protocol (Symbol.iterator → next()).
How to Explain Symbol.iterator to an Interviewer
What is Symbol.iterator?
Used for a short Symbol.iterator example a script in the browser Not just the heading
Give one small example of Symbol.iterator.
the smallest Symbol.iterator example you can type The well-known symbol that makes a value iterable
What mistake do beginners make with Symbol.iterator?
only saying “Symbol.iterator” with no example Show the fix
Where do you use Symbol.iterator?
a script in the browser a short Symbol.iterator example