Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_.isUndefined implementation

Why is underscore.js's isUndefined defined this way?

_.isUndefined = function(obj) { return obj === void 0; };

Why can't this work?

typeof obj === 'undefined'

like image 353
Sudheer Someshwara Avatar asked Nov 19 '12 23:11

Sudheer Someshwara


1 Answers

Ok, for a start typeof obj === 'undefined' is slower as you can easily verify.

The question then is why make the comparison

obj === void 0 

vs

obj === undefined

Let's see:

void 0; returns the result of the unary operator void which will always return undefined (i.e. void 1 would make no difference)

undefined points to the global variable undefined.

Under normal circumstances the two are the same. I presume though void 0 is preferred because it is possible to shadow undefined with a local variable undefined :) This is idiotic but it happens.

like image 108
ggozad Avatar answered Oct 20 '22 00:10

ggozad