In the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
The for...of
construct is described to be able to
As a sidenote, BEWARE about the definition of iterable. If you're coming from other languages you would expect that something you can iterate over with, say, a for
loop is iterable. I'm afraid that's not the case here where iterable means something that implements the iteration protocol.
To make things clearer all examples above return false
on this object {a: 1, b: 2}
because that object does not implement the iteration protocol. So you won't be able to iterate over it with a for...of
BUT you still can with a for...in
.
So if you want to avoid painful mistakes make your code more specific by renaming your method as shown below:
/**
* @param variable
* @returns {boolean}
*/
const hasIterationProtocol = variable =>
variable !== null && Symbol.iterator in Object(variable);