BG Photo by John Daines on Unsplash

Void in Javascript

Krishna Damaraju
Nov 11 · 2 min read

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

2. In Conditional Statements

While comparing a undefined variable or data to undefined

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

Small Things

Coding tips for beginners

Krishna Damaraju

Written by

JS Developer working with EmberJs and ReactJs. Find me at https://krishnasarath.xyz

Small Things

Coding tips for beginners

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade