Get my new tutorials in your inbox every week

The JavaScript void operator

javascript void operator

Did you know that JavaScript has a void operator just to explicitly return undefined? Its a unary operator, meaning only one operand can be used with it. You can use it like shown below — standalone or with a parenthesis.

void expression;
void(expression);

Let’s see some examples of the void operator

void 0; //returns undefined
void(1); //returns undefined

void 'hello'; //undefined
void {}; //undefined
void []; //undefined

void myFunction(); 
void(myFunction());

But why the void operator was needed at all?

Why the hell do you need a special keyword just to return undefined instead of just returning undefined? Well, the reason is before ES5 you could actually assign a new value to the original undefined like so undefined = “js snippet”, and most browsers would support it. So as to return the original undefined and just to be double sure the void operator was used.

More examples

//just a normal function
function test() {
    console.log('hello');
    return 2;
}
//lets call it
test(); //output is hello followed by 2

//now lets try with void
void test(); //output is hello followed by undefined

So in the example above, void cancels the return from the function and explicitly returns undefined. But the log is anyways printed.

So now that you are aware of it, give the JavaScript void operator a try. Would you?

Read more from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

Follow @JavaScriptSnip1 for your daily dose of JavaScript. It’s another channel that I maintain. Similar code snippets are also available on this Github repo (with an aim to be the largest repository of JavaScript snippets.). Contributions are open via Pull Requests.

Share your thoughts below in the comments section or give me a shout.

Write a Comment

Your email address will not be published. Required fields are marked *