nCardot
nCardot

Reputation: 6595

In a user-defined iterable with [Symbol.iterator], what is [Symbol.iterator] called?

In a tutorial that explains how to make a user-defined iterable, it says

So how do we implement the iterable protocol on our own objects? We do that by defining a method with a key of Symbol.iterator.

Is it correct to call [Symbol.iterator] it a key, given it's part of a method? My understanding is a key can only be part of a property (a property is comprised of a key and a value), and a method is a function used inside an object.

For reference, this is the example from the tutorial:

class UserCollection {
  constructor(users) {
    this.users = [].concat(users);
  }

  [Symbol.iterator]() {
    let i = 0;
    let users = this.users;

    return {
      next() {
        if (i < users.length) {
          return { done: false, value: users[i++] };
        }

        return { done: true };
      }
    };
  }
}

Upvotes: 0

Views: 189

Answers (2)

Stefan Octavian
Stefan Octavian

Reputation: 620

I think that you are confused about the terms key, property and method. In javascript, methods are just functions assigned to properties. For example:

obj = {
   method() {}
}

is analogous to

obj = {
  method: function() {

  }
}

The confusion comes from the fact that the syntax above is a shorthand and it's actually just syntactic sugar that was introduced in ES6. Untill then, assigning an anonymous method to a property was the only way of defining methods to objects. So, yes [Symbol.iterator] is a key. Because

obj = {
  [Symbol.iterator]() {}
}

is almost* the same as

obj = {
  [Symbol.iterator]: function() {}
}

*Almost the same because the shorthand also gives the function a different toString() method that the default one. If you do console.log(obj[Symbol.iterator]) in both scenarios you will get [Symbol.iterator]() {} and function() {}

Upvotes: 2

Claies
Claies

Reputation: 22323

In ES6, you can define method names via expressions, using []. This allows you to create method names that are computed (computed keys).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions

For example, The following are all equivalent:

class Foo {
    myMethod() {}
}

class Foo {
    ['my'+'Method']() {}
}

const m = 'myMethod';
class Foo {
    [m]() {}
}

All 3 create Foo.myMethod().

In your case, [Symbol.iterator] allows you to get the iterator Symbol, and assign that Symbol as the method name.

Upvotes: 5

Related Questions