Update 2018-07-25
It's been nearly five years since this post was first made, and JavaScript has come a long way. In repeating the tests in the original post, I found no consistent difference between the following test methods:
abc === undefined
abc === void 0
typeof abc == 'undefined'
typeof abc === 'undefined'
Even when I modified the tests to prevent Chrome from optimizing them away, the differences were insignificant. As such, I'd now recommend abc === undefined
for clarity.
Relevant content from chrome://version
:
- Google Chrome: 67.0.3396.99 (Official Build) (64-bit) (cohort: Stable)
- Revision: a337fbf3c2ab8ebc6b64b0bfdce73a20e2e2252b-refs/branch-heads/3396@{#790}
- OS: Windows
- JavaScript: V8 6.7.288.46
- User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Original post 2013-11-01
In Google Chrome, the following was ever so slightly faster than a typeof
test:
if (abc === void 0) {
// Undefined
}
The difference was negligible. However, this code is more concise, and clearer at a glance to someone who knows what void 0
means. Note, however, that abc
must still be declared.
Both typeof
and void
were significantly faster than comparing directly against undefined
. I used the following test format in the Chrome developer console:
var abc;
start = +new Date();
for (var i = 0; i < 10000000; i++) {
if (TEST) {
void 1;
}
}
end = +new Date();
end - start;
The results were as follows:
Test: | abc === undefined abc === void 0 typeof abc == 'undefined'
------+---------------------------------------------------------------------
x10M | 13678 ms 9854 ms 9888 ms
x1 | 1367.8 ns 985.4 ns 988.8 ns
Note that the first row is in milliseconds, while the second row is in nanoseconds. A difference of 3.4 nanoseconds is nothing. The times were pretty consistent in subsequent tests.