What is the use of binding to `undefined` instead of` null`

I often see that when a function needs to be called with bound parameters in a specific context, undefined most often preferred over null as a context choice, as in:

 f.call(undefined, param1, param2) 

more preferable:

 f.call(null, param1, param2) 

I am wondering if there is any special reason for this?

+6
source share
2 answers

What is the use of binding to undefined instead of null ?

I do not think so. From 10.4.3 Entering the function code :

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

But if the code is strict, this will either be null or undefined . f could be implemented to distinguish these cases, but for me this is not a very likely scenario.

+6
source

In javascript, undefined goes past a script in which a value has not been set. For example, if you are looking for a property on a model that does not exist, it will give undefined.

Not so strange to have code like this:

var k;

// do something (maybe by setting k)

alerts (k);

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

In short, this is still a preference, but using undefined, you will most likely catch cases where the values ​​were not initialized or did not try to access the properties of objects that do not exist.

Not sure if this answers your question.

+1
source

Source: https://habr.com/ru/post/985370/


All Articles