Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand "return obj === void 0" in the source of underscore? [duplicate]

Possible Duplicate:
What does “javascript:void(0)” mean?
What does void 0 mean?

In the file http://underscorejs.org/underscore.js, you can see such a code block:

// Is a given variable undefined?
_.isUndefined = function(obj) {
  return obj === void 0;
};

I don't understand the void 0 part, it's very strange. How to understand it?

like image 903
Freewind Avatar asked Jul 10 '12 08:07

Freewind


2 Answers

This is the console output

>typeof void 0
"undefined"
>void 0 === undefined
true
>"undefined".length
9
>"void 0".length
6

I think they are trying to save 3 bytes of file size ;)

Edit: This SO answer makes more sense of using void 0, as undefined is just a property of window object and is mutable. Hence void 0 is a trusted way to generate undefined across browsers

like image 52
Tamil Avatar answered Oct 20 '22 04:10

Tamil


In javascript (since 1.1), the void operator is used to evaluate an expression and return undefined.

See ECMAScript Language Specification of the void operator

So void 0 is a correct and standard way to produce undefined.

As it is an operator, no parenthesis are needed.

like image 35
Denys Séguret Avatar answered Oct 20 '22 03:10

Denys Séguret