Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use underscore's isUndefined(x) over x === undefined? [closed]

Is there any benefit in using isUndefined? Is it worth an extra function call? It's not any more readable.

like image 344
sdr Avatar asked Jun 04 '14 16:06

sdr


People also ask

Why is my variable undefined JavaScript?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

How do you know if a variable is undefined?

To check if a variable is undefined, you can use comparison operators — the equality operator == or strict equality operator === . If you declare a variable but not assign a value, it will return undefined automatically. Thus, if you try to display the value of such variable, the word "undefined" will be displayed.

Why is object undefined?

undefined means that the variable value has not been defined; it is not known what the value is.

Is void 0 the same as undefined?

The void operator evaluates an expression and returns the primitive value undefined. void 0 evaluates 0 , which does nothing, and then returns undefined . It is effectively an alias for undefined .


1 Answers

The name undefined can be shadowed. That is, somebody could do this

var undefined = 5;

and break the code that uses x === undefined (see note at bottom). To get around this safely, you can use

typeof x === 'undefined'

or

x === void 0

which is exactly what the underscore function does.


Note: Since ECMAScript 5, undefined is read-only. In older browser, the global undefined can be redefined. Even in newer browsers, undefined can be shadowed by a local variable:

function f() {
  var undefined = 5;
  return undefined;
}
f() // returns 5
like image 117
Peter Olson Avatar answered Oct 05 '22 11:10

Peter Olson