0
    Array.prototype.forEach = function(callback, context) {
        for (var i = 0; i < this.length; i++) {
            callback.call(context || null, this[i], i, this);
        }
    };

    ["a", "b", "c"].forEach(function(value, index, array) {
        assert(value,
                "Is in position " + index + " out of " +
                        (array.length - 1));
    });

I don't fully understand why null is used here. I guess when I use the invoke foreach, if I miss the context parameter, it will replace it with null? Will callback.call(context || null, this[i], i, this) execute? Can someone explain this for me?

2 Answers 2

1

It shouldn't actually be there. undefined and null have the same effect when passed as the this argument to Function.prototype.call (the this argument of the function is set to undefined).

Sign up to request clarification or add additional context in comments.

2 Comments

so even i pass null or undefined to Function.prototype.call, the Function.prototype.call still can execute ?
@joesmith: The this argument can take any value. In non-strict mode, if you pass null or undefined as the this argument, this will be undefined in the function.
1

If you pass a falsy value for 'context', (context || null) will result in a null. JS will pass null as the first parameter into callback.call(). The first parameter is the this for the callback function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.