DEV Community

loading...

TIL: Symbols can be used to override for..of in Javascript

graciano profile image graciano codes ・1 min read

If, for some reason, I implement an iterable object in javascript, I can do like:

class NiceIterable {
  *[Symbol.iterator]() {
    let i = 0;
    while(this[i] !== undefined) {
      yield this[i++];
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

And then, something like:

let foo = new NiceIterable();
foo[0] = 'this';
foo[1] = ' is';
foo[2] = ' weird';
foo[3] = ' and cool';
for (let elem of foo) console.log(elem); // this is weird and cool
Enter fullscreen mode Exit fullscreen mode

😶😮🤯

A thing I didn't quite understand is the * character in the line *[Symbol.iterator]() {. Is it an unary operator? Please tell me if you know.

Source is this really good guide on Symbols.

Discussion

pic
Editor guide
Collapse
sergiodxa profile image
Sergio Daniel Xalambrí

The * is used to define that method as a generator function which allows you to use the yield keyword.

Collapse
graciano profile image