Search code examples
javascriptarraysiteratortypeerror

Symbol.iterator mysteriously changes to null or undefined upon calling


I have a JavaScript class that wraps an array. The class looks something like this.

class Store {
    constructor() {
        this._store = [];
    }
}

I am trying to define a Symbol.iterator, so a class instance can be iterated through with for example a for...of loop.

The class is designed in such a way, that the _store parameter can be null. My solution for defining Symbol.iterator function in compliance with this is as follows

class Store {
    ...

    [Symbol.iterator]() {
        const iterator = (this._store || [])[Symbol.iterator]
        return iterator();
    }
}

The idea behind this is, that if the _store holds an array, this code will return _store[Symbol.iterator], otherwise it will return iterator of an empty array.

This function, however throws the following error, which points at the line which the iterator is being called and returned.

TypeError: Cannot convert undefined or null to object

The following code illustrates the issue. While the iterator is successfully evaluated as a function, calling it indicates, that the value being called is undefined or null.

class Store {
    constructor() {
        this._store = [];
    }

    [Symbol.iterator]() {
        const iterator = (this._store || [])[Symbol.iterator]
        console.log(iterator); // output: function values()
        return iterator(); // throws TypeError, even though a function is being called
    }
}

const store = new Store();
console.log([...store]); // calls Symbol.iterator, throws TypeError

It is also worth noting, that with the following modification to the class iterator definition, the code works and behaves as expected, though without robustness to _store being null.

class Store {
    ...

    [Symbol.iterator]() {
        return this._store[Symbol.iterator]();
    }
}

Any ideas to why this is happening?


Solution

  • When you assign a function to a variable, then call it using that variable, you lose the this reference in the function.

    E.g.:

    const obj = {
        foo: "foo",
        bar() { return this.foo; },
    };
    
    console.log(obj.bar()); // "foo"
    
    const bar = obj.bar;
    
    console.log(bar()); // undefined or error, depending on strict mode
    

    In your code, this is what is happening in the following line:

    const iterator = (this._store || [])[Symbol.iterator]
    

    You are stripping the this reference away from the [Symbol.iterator] function, and then it fails (internally).

    In order for the iterator to work, you need to preserve the this reference either by using bind() or by avoiding assign the function to a different variable:

    class Store {
        constructor() {
            this._store = [];
        }
    
        [Symbol.iterator]() {
            // Assign the object, not the function, to a variable:
            const store = this._store ?? [];
            return store[Symbol.iterator]();
                // ^^^^^ keep either _store or [] as the 'this' reference
        }
    }
    
    const store = new Store();
    console.log([...store]);
    

    For more information on this, see this MDN article:

    "The value of this in JavaScript depends on how a function is invoked (runtime binding), not how it is defined. When a regular function is invoked as a method of an object (obj.method()), this points to that object. When invoked as a standalone function (not attached to an object: func()), this typically refers to the global object (in non-strict mode) or undefined (in strict mode)."
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this


    As to the question you asked in the comments:

    inlining the expression with return statement works:

    js return (this._store || [])[Symbol.iterator]();
    

    But consider the following example:

    class Store {
      // ...
      [Symbol.iterator]() {
        return (this._store[Symbol.iterator] || [][Symbol.iterator])();
      }
    }
    

    Everything is inline, no variables are being assigned or scopes changing. Yet, it throws Type Error. Why is that?

    It helps to see your example not as single expression, but as a series of expressions.

    This expression will return a function. The function was defined on the object's prototype, but when the expression returns the value it will return it as it's own independent value:

    (this._store[Symbol.iterator] || [][Symbol.iterator])
    

    You then invoke that returned function:

    _returned_function()
    

    Basically, it's semantically identical to:

    const _function = (this._store[Symbol.iterator] || [][Symbol.iterator]);
    const _result = _function();
    return _result;
    

    Or, put another way:

       ________[methodName]()
    // ^^^^^^^^
    // This expression must resolve to an *object*
    // Otherwise, the function will be invoked using global context