Is there any benefit in using isUndefined? Is it worth an extra function call? It's not any more readable.
Asked
Active
Viewed 841 times
7
-
2@JoeSwindell Read the title – Peter Olson Jun 04 '14 at 16:48
-
@JoeSwindell As compared to `x === undefined`. – Uyghur Lives Matter Jun 04 '14 at 16:48
-
1Well, it does `_.isUndefined = function(obj) { return obj === void 0; };`, so it's obviously not exactly the same. – adeneo Jun 04 '14 at 16:50
-
^ and based on that, this is a duplicate -> **http://stackoverflow.com/questions/4806286/difference-between-void-0-and-undefined** – adeneo Jun 04 '14 at 16:51
-
.isUndefined returns true in underscore.js if it is undefined. It's not the same. – Joe Swindell Jun 04 '14 at 16:53
-
@adeneo That question is specifically about `void 0` vs `undefined` with no mention about `_.isUndefined()`, so I would say this is not a duplicate. – Uyghur Lives Matter Jun 04 '14 at 16:53
-
@cpburnz - and read my comment, `void 0` is exactly what underscore does, and it's the only thing it does, so why would it not be dupe. – adeneo Jun 04 '14 at 16:55
-
@adeneo If this question was to be closed as a duplicate, a person would be directed to that other question talking about the difference between `void 0` and `undefined` which to them would not necessarily answer how `_.isUndefined()` differs from `undefined` unless they knew how `_.isUndefined()` was defined in which case they would not be looking up this question but the other. – Uyghur Lives Matter Jun 04 '14 at 16:59
-
The real answer is that using `void` ensures the object is compared against `undefined`, as `void 0` returns `undefined`, and `void` is a reserved keyword so it can't be overwritten in any scope, shape or form, writing `var void` is in fact a syntax error. – adeneo Jun 04 '14 at 17:00
1 Answers
9
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

Peter Olson
- 139,199
- 49
- 202
- 242
-
1In EcmaScript 5 `undefined` is read-only, so it's not an issue, but you could declare a local variable with that name, but then it would generally be your own mistake. – adeneo Jun 04 '14 at 16:53