The JavaScript void operator

Joseph Khan
tajawal
Published in
1 min readSep 18, 2019

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);

But why?

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.

Some examples,

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

Give it a try, would you!!

This was originally published by Joseph on behalf of JavaScript snippets (An Useful collection of JavaScript Snippets….still growing)

--

--

Joseph Khan
tajawal
Writer for

Engineering Manager | Author & Speaker. I work with one of the largest OTA (Online Travel Agencies) in the Middle East https://josephkhan.me/