Symbol.iterator mysteriously changes to null or undefined upon calling [closed]

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?

9

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

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật