Skip to content Skip to sidebar Skip to footer

What's The Benefit Of Binding To `undefined` Instead Of `null`

I often see that when a function needs to be called with bound parameters in no particular context the undefined is more often than not is preferred over the null as a choice of co

Solution 1:

What's the benefit of binding to undefined instead of null?

I don't think there is any. From 10.4.3 Entering Function Code:

  1. If the function code is strict code, set the ThisBinding to thisArg.
  2. Else if thisArg is null or undefined, set the ThisBinding to the global object.
  3. ...

So, if the code is not strict, in both cases this will be set to the global object.

But if the code is strict, this will actually either be null or undefined. f could be implemented to distinguish these cases, but that doesn't seem to be a very likely scenario to me.

Solution 2:

In javascript, undefined extends past the scenario where a value has not been set. For instance, if you are looking for a property on a model that does not exist, it will yield undefined.

Its not that odd either to have code like this:

var k;

//do something (possibly setting k)

alert(k);

If the value has not been set, it will be undefined rather than null.

Long story short, it is still a preference, but by using undefined you are more likely to catch the cases where values have not been initialized or try accessing properties of objects that do no exist.

Not sure this answers your question.

Post a Comment for "What's The Benefit Of Binding To `undefined` Instead Of `null`"