What is a real-world use-case for JavaScript's void operator?

Viewed 628

Why would someone write:

function () {
    if (err) {
        return void console.log(err)
    }
}

instead of:

function () {
    if (err) {
        console.log(err)
        return
    }
}

Has anyone used the void operator at all? I have seen it being used as in the example case above, but very very rarely.

Update

console.log might be a poor example as it returns void itself. Let me show another use I have seen in an express app:

function (req, res) {
    ...
    // Some error occurred
    if (err) {
        return void res.send(foo)
        // `send` returns a `Response` instance
    }
}

In eslint's source code for example, it is being used quite a lot:

config-initializer.js

jshint.js - BIG FILE WARNING!

consistent-return.js

3 Answers

Use Case 1

In my code, I always have ESLint's no-floating-promises enabled, which makes sure that I never forget to await a promise (flashback to the hours of debugging I've spent only to find that's what it was).

However, sometimes there are also promises that I want to leave unawaited, to let them run in the background. In those cases the void keyword makes it look to ESLint as though the promise is being consumed, when it really isn't:

fetch('https://google.com/') // ESLint error: no-floating-promises

void fetch('https://google.com/') // Does the same thing; no ESLint error

Use Case 2

In other people's code, you'll often see it in combination with the literal 0:

{ code: "function foo() { if (true) return; else return void 0; }", options: [{ treatUndefinedAsUnspecified: true }] },
--------------------------------------------------------^^^^^^ HERE

This can be done for one of two reasons:

  • See @sabithpocker's answer: Because undefined can be shadowed and void cannot. Especially useful when code is mixed with arbitrary user code, for example in an optimizer; where it's conceivable the user may have created a variable named "undefined".
  • Because void 0 is shorter than undefined. Especially in compiled code (for example if it's been passed through terser or webpack), it's important to minimize the amount of characters in the bundle. void 0 has 6 characters, while undefined has 9, so it's an easy three character win for the optimizer to replace all instances of undefined with void 0.

TL;DR: The void keyword can be used to:

  • Escape certain linter rules
  • Replace undefined with void 0 to save three characters
Related