Vasyl Stokolosa

@shystruk

Is void forgotten? JavaScript: The Useful Parts

Photo by Johnson Cameraface on Flickr
In many languages, void is a type that has no values. In JavaScript, void is a operator that takes an operand and return undefined. This is not useful, and it is very confusing. Avoid void. ~ Douglas Crockford. JavaScript: The Good Parts

If you agree with that statement I do not want to waste your time, jump out from here and keep saving the world. 😎 If not, let’s discover why void is useful and you should not avoid it.

Why void confuses?

void 0 === undefined //true 😰 😱 😵

Why? How? What is void? Is this even JavaScript?

Answers which I got when asked developers about the void and the main confuse here is that developers forgot or have not known or find strange.

The void operator evaluates the given expression and then returns undefined. That is all what you need to know about void operator.

How void can be useful?

1. Evaluate expression and jump out from a function

One time I’v done a code review and found a method like that:

function doStuff(a) {
if (a) {
doSomething()
} else {
doSomethingElse()
return
}
    doSomethingMore()
}

So, from this method you may see that in case doSomethingElse() we return undefined and jump out from the function. Let’s save one line and make it more readable with void.

function doStuff(a) {
if (a) {
doSomething()
} else {
return void doSomethingElse()
}
    doSomethingMore()
}

From void description you know that it evaluates doSomethingElse() and return undefined. That exactly what we need 👍

2. Check for undefined

Old browsers allowed undefined to be re-assigned undefined = 'test'. However, this was fixed in 2009 with ECMAScript 5.

If you need to support old browser e.g. IE8, here is a helper function 😊

function isUndefined(value) {
return value === void 0
}

3. preventDefault() behavior for a link

We all know that a tag without href attribute is not valid, but in HTML5 href attribute is not required, so you can omit.

Somehow, if you need to prevent hrefworks use void.

<a href="javascript: void(0)">About</a>

4. Immediately Invoked Function Expressions

When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration.

void function IIFE() {
// do something ...
}()

Conclusion

void is a simple operator and I find it useful. I guess, more developers do not use it because they have not touched it while learning. Of course, if a team find it confused better to discuss. In help, ESLint has the rule (no-void). Happy coding! 😎

👏 Thank you for reading. Suggestions, comments, thoughts are welcome :)

If you like this, clap, follow me on medium, twitter, github share with your friends ✌️

More by Vasyl Stokolosa

Topics of interest

More Related Stories