I started to learn the apply
function from this doc
In the following example, the function invocation with apply
and that without apply
have the same output.
console.log(Math.max(5, 6, 2, 3, 7)); // output:7
console.log(Math.max.apply(null, [5, 6, 2, 3, 7])); // output:7
However, when I adopted the same way on the following example, the outputs are different.
class Animal {
speak() {
return this;
}
}
let obj = new Animal();
let speak = obj.speak;
console.log(speak()); // output:undefined
console.log(speak.apply(null, [])); // output:null
It seems passing null
as the 1st argument of apply
may change the behavior of the function. Using undefined
does not have this side effect. For example:
console.log(Math.max.apply(undefined, [5, 6, 2, 3, 7])); // output:7
console.log(speak.apply(undefined, [])); // output:undefined
So is it safer to use undefined
than null
in most cases? (suppose we only focus on cases where there is no this
object for the function call)