Thought leadership from the most innovative tech companies, all in one place.

What is “void 0” in JavaScript?

Is it similar to undefined? Should we avoid it or not?

Photo by Andrea De Santis on Unsplash

Hi, I'm a software engineer, and welcome to my blog. Today, we are going to discuss void 0.

What we should know about void 0

In older versions of JavaScript, you wouldn't have found void 0 expressions. The keyword is **void **which **is **undefined.

image

void 0
void (0)
void "hello"
void (new Date())
//all will return undefined

undefined is mutable

Photo by Valentin Lacoste on Unsplash

So why do we use **void 0 **as an alias for undefined?

One of JavaScript's quirks is that it is not a reserved keyword. Instead, it is a property of the global object.

According to wtjs.com,

Undefined is nothing but a global variable name without a default value. Therefore, its primitive value is undefined. You can change the value of undefined:

var a = {};
a.b === undefined; // true because property b is not set
undefined = 42;
a.b === undefined; // false

Due to the mutability of undefined, it is generally a better idea to check for undefined-ness through typeof:

var a = {};
typeof a.b == 'undefined'; // always true

The undefined global variable has been disabled in ES5 as shown above.

image

Look at the variable disfunction when the variable will be printed. It is still undefined as a value.

The ESLint rule, no-undefined, disallows the use of undefined as a variable name and prevents shadowing issues.

How about void 0 as an undefined value? Should we avoid this?

Yes, you don't need void 0 in ES5 and newer. Keep your code readable and let the minifiers optimize the performance.

Alert!

If you guys happen to be from Indonesia and want to support me to write more and more, hopefully, you can contribute a little bit from your wallet. You can share your gift in some ways, thank you.

Saweria

https://saweria.co/pandhuwibowo

image

Trakteer

https://trakteer.id/goodpeopletogivemoney

image

Reference

void operator - JavaScript | MDN

JavaScript Void 0 - What Does javascript:void(0); Mean?

What does void 0 mean?

JavaScript: what does "void 0" mean?

You Don't Need void 0 in JavaScript

wtfjs - a little code blog about that language we love despite giving us so much to hate




Continue Learning