Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the benefit of binding to `undefined` instead of `null`

Tags:

javascript

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 context, as in:

f.call(undefined, param1, param2)

is preferred over:

f.call(null, param1, param2)

I'm wondering if there is any particular reason for this?

like image 367
Max Koretskyi Avatar asked Apr 17 '15 17:04

Max Koretskyi


People also ask

Is it better to use undefined or null?

Only use null if you explicitly want to denote the value of a variable as having "no value". As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing".

Is it OK to return undefined?

A function returns undefined if a value was not returned . Note: While you can use undefined as an identifier (variable name) in any scope other than the global scope (because undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug.

What is the difference between null & undefined?

Definition: Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript. Undefined: It means the value does not exist in the compiler.

Is undefined === null?

In JavaScript, undefined is a type, whereas null an object. It means a variable declared, but no value has been assigned a value. Whereas, null in JavaScript is an assignment value. You can assign it to a variable.


1 Answers

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.

like image 86
Felix Kling Avatar answered Oct 12 '22 12:10

Felix Kling