This question already has an answer here:
I'm studying the annotated source code of Underscore.js.
http://underscorejs.org/docs/underscore.html#section-41
Here's the _.first method:
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
return (n == null) || guard ? array[0] : slice.call(array, 0, n);
};
Question:
Why 'return void 0;' and not just 'return;' ? As far as I know return implicitly returns undefined (the value!) from a function. Just like 'return void 0' does.
In the MDN reference for the void operator it states:
So it is indeed equivalent to
undefined
but the problem with theundefined
variable is that it can be redefined as something else. Personally I would always simplyreturn;
because it consistently yields the exact same result (as in:(function() {})() === void 0
).Clarification
Since some commenter consider this not an appropriate answer:
(function() {})() === void 0
always yields true which means that it is exactly the same asreturn;
. So you can consider this an inconsistency in the Underscore library as plain return statements are used in other places (yes, even there it can happen).Minification and optimization
Another addendum, it looks as if it also doesn't optimize any better during minification. Using the closure compiler the
return void 0;
vsreturn;
version of the above code sample is still about 5% bigger.