Question presented to candidate: "What's actually the difference between an 'iterator' and an 'iterable' in JavaScript — aren't they the same thing? And if I hand you an object with just a next() method, will for...of work on it directly?"
What a strong answer should cover:
- 📌 Interview term: the iterator protocol — an object is an iterator if it has a
next()method that returns a real{ value, done }object each call — verified directly, hand-driving one through 4 calls, including the final{ value: undefined, done: true }. - 📌 Interview term: the iterable protocol — an object is an iterable if it has a
[Symbol.iterator]()method that RETURNS an iterator — a genuinely separate, distinct protocol from being an iterator itself. - 📌 Interview term: the real, direct answer to the prompt — verified directly: a raw object with only a
next()method (an iterator, but not an iterable) genuinely fails with a realTypeErrorwhen used directly withfor...of—for...of, spread syntax, and destructuring all specifically look for[Symbol.iterator], notnext()alone. - 📌 Interview term: built-in iterables — verified directly: arrays and strings genuinely have a real, built-in
[Symbol.iterator], while a plain object genuinely does not — this is exactly whyfor...ofworks natively on arrays/strings/Maps/Sets but throws on a plain object (covered in more depth in this bank's ownfor...ofvs.for...inquestion). - A precise answer names that many objects are BOTH iterators and iterables at once — a generator object (covered in this bank's own dedicated generator-function question) genuinely has both a working
next()AND its own[Symbol.iterator]that just returns itself, which is exactly why a generator can be driven manually with.next()calls AND used directly withfor...of.
Clarifying questions expected:
- None — this is a definitional/technical question; directly answering whether a bare iterator alone works with
for...of(it does not) is the strong signal.
Code / implementation expected: Yes — a real, manually-implemented iterator AND a separate real iterable wrapping it, verified working differently with for...of, is the clearest, most convincing demonstration.