0

I'm trying to assign an iterator method to a variable, but I get the error 'Cannot convert undefined or null to object' when I try to run it.

Works:

test = [1][Symbol.iterator]();
test.next(); // Returns 1

Doesn't work

test = [1][Symbol.iterator];
test().next(); // Cannot convert undefined or null to object

Why would I get an error in the second case?

Adam Prax
  • 6,413
  • 3
  • 30
  • 31
  • 1
    Because you're not preserving `this`. [How does the "this" keyword work, and when should it be used?](https://stackoverflow.com/q/3127429) | [How to access the correct `this` inside a callback](https://stackoverflow.com/q/20279484) – VLAZ Feb 12 '23 at 13:19
  • `test.bind(array)().next()` where `array` is the array with values. – Nina Scholz Feb 12 '23 at 13:27

1 Answers1

0

In the first example, you assign the result of the Symbol.iterator method invocation to object [1] to the variable test. Therefore, test is an iterable object with a next method that can be called.

But in the second example, you are assigning only the reference to the Symbol.iterator method to the test variable, not the result of its invocation. Therefore, test is not an iterable object and cannot be called as a function.

S. Wasta
  • 599
  • 9
  • 35
  • test is a function in the second case though `test = [1][Symbol.iterator]` `typeof test // returns "function"` – Adam Prax Feb 12 '23 at 13:24