← Back tothis vs that

undefined vs void

Written byPhuoc Nguyen
Created
16 Jul, 2020
Category
JavaScript
`void` is an operator that evaluates a given expression and then returns `undefined`.

Difference

In the modern browsers which supports ES5, there's no difference between using the `void` operator and the `undefined` value directly:
js
void 0 === undefined; // true
void 1 === undefined; // true
void 'Foo' === undefined; // true
However, in the old browsers which run ES3 engine, `undefined` is a global property and can be changed.
js
// In ES3
console.log(undefined);
var undefined = 'foo';
console.log(undefined); // 'foo'
On the other hand, it's not possible to override the `void` operator. Hence, `void` is used as a replacement for `undefined` to get the `undefined` value in a safe way.
In ES5, it's impossible to override `undefined` because it's set `Writeable` as `false`.

Good to know

  1. `void` is an operator, not a function. So we don't need to wrap the expression in parentheses. `void 0` is equivalent to `void(0)`.
  2. There are minifiers which use `void 0` to shorten `undefined`.
  3. If you use immediately-invoked function expression (known as IIFE), `void` can be used to treat the `function` keyword as an expression, not a declaration.
    Assume that we want to execute the following IIFE function:
    js
    function run() {
    console.log('Executed');
    }();
    then we can either use `void`
    js
    void (function run() {
    console.log('Executed');
    })();
    or wrap the function in parentheses as below:
    js
    (function run() {
    console.log('Executed');
    })();
  4. `void` can be used to avoid the side effect when using with arrow functions.
    As we know, ES6 arrow functions allow to use the return value of function by omitting the braces from the function body.
    js
    const sum = (a, b) => a + b;
    In some cases, we don't intend to use the return value of function, because it can lead to a different behavior. Let's say that we are going to handle the `click` event of a button:
    js
    button.onclick = () => doSomething();
    It works as usual until someone changes `doSomething`, and makes it return a `boolean` value. In the case it returns `false`, the default behavior of the `click` event will be skipped, and it maybe the thing you don't want to.
    Passing the result to `void` will ensure that it doesn't change the behavior of arrow function regardless the result of executed functions:
    js
    button.onclick = () => void doSomething();
  5. The advantage of using `void` with arrow functions can be seen in modern libraries such as React, Svelte.
    These libraries allow us to execute a function right after a component mounted to the DOM. For example, React provides `useEffect`, Svelte has `onMount`.
    If we return a function inside the callback, then the function will be invoked to clean up things, free the memory before the component is removed from the screen.
    js
    // React example code
    useEffect(() => doSomething());
    It can produce bugs at run time. To avoid that, we can either use `void`
    js
    useEffect(() => void doSomething());
    or using the braces:
    js
    useEffect(() => {
    doSomething();
    });

Good practice

The `void` operator has been used in the URL prefixed with `javascript:`.
By default, the browser will evaluate the code when following a `javascript:` URI, and then replaces the contents of page with the returned value.
To prevent the default behavior, the code must return `undefined`. That's why we have been seeing the following code:
js
<a href="javascript: void(0);" onclick="doSomething">
...
</a>
Nowadays, using `javascript:` protocol isn't recommended. It can create a security issue since user can put unsanitized input in the event handler:
js
<a href="javascript: alert('unsanitized input')">...</a>
Starting from v16.9.0, React also deprecates the usage of `javascript:` URLs.

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn