BG Photo by John Daines on Unsplash

Void in Javascript

Krishna Damaraju
Small Things
2 min readNov 11, 2019

--

Void is unary operator, which when prepended to any expression/function returns undefined after the execution of the expression/function.

It even discards the functions default return value and explicitly returns undefined

A few of the common use cases of the void -

1. Usage with Inline Javascript

Best example for this is javascript: void 0. It is commonly used with the anchors href attribute to prevent the route change or URL pollution (by appending # to the current URL) on clicking a link element.

Other ways to achieve the same

<a href=“javascript: void(0)” onclick=“..”>Click me</a><a href=“javascript: return false;” onclick=“..”>Click me</a>

2. In Conditional Statements

While comparing a undefined variable or data to undefined

if(user.session === void(0)) { // take to login }

3. With functions

Some times a function is supposed to return an undefined or null after some logical operation or comparison.

4. Othe uses cases on MDN

🤔 Reason for VOID

void is introduced to handle the shadowing of undefined in the pre-ES5 where undefined on the global scope can be overridden or shadowed.

Eg., var undefined = new Data() was totally possible that time.

But don’t worry, The above is not possible in the ES5 and followed versions but it is rumoured to be still available in the functions scope. Need to check on that.

There is a Eslint rule to prevent the usage of the void operator.

If you are supporting the wide spectrum of users, i’d say stick to void for some more time 🤷‍♂

🔗 Helpful Links

Cheers 🙌
KD

--

--