JavaScript void vs. undefined

July 29, 2014

Did you know that JavaScript has a void operator?

Well, it does.

What is it used for

Mostly, I’ve seen the void operator used to trigger the catch part of a try-catch. Something like this:

try {
    throw void(0);
} catch (e) {
    console.log('This will always run');

The other, and perhaps more common, way of achieving this is to just throw undefined instead of void(0).

So, what’s the difference?

undefined vs. void(0)

Well, it turns out back in the day you could actually change the value of the global undefined. That’s been changed in JavaScript 1.8.5.

However, you can still use undefined as a variable name as long as it’s not in the global scope. So, unfortunately, this could be done which would cause problems with your try-catch:

function myObject() {
    var undefined = 'LOL';

    function coolFunction() {
        try {
            throw undefined;
        } catch (error) {
            console.log(error); // 'LOL'
    return coolFunction;

Honestly, it’s probably not a very realistic use-case, but it seems like the most common reason I see people using void(0).