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

4

6

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

Branching answered 5/6, 2017 at 6:16 Comment(7)
Possible Duplicate/Related What is the point of void operator in JavaScript?Bandmaster
@Bandmaster that example explains the use case in a <script> tag, which I am aware of. I'm more curious about the use within a script itself.Branching
@JaromandaX I've updated with a real example I've seen on an npm module. console.log is a poor example.Branching
yeah, saw that - the only reason I can see is to reduce the code by 1 line!Salop
@JaromandaX I found the repo I saw void being used in, eslint is one amongst themBranching
yeah, I've used void when I know an argument to a function is unused to avoid the unused var "warning"Salop
Interesting. I've never seen it before, but now I think I'd use it in cases where I'm writing a function that isn't expected to return any particular value, but it sometimes does because I write if (...) return f(...). It would be cleaner to do if (...) return void f(...) rather than have my function's return value depend on another's.Diaphanous
S
3

One use case is that it always returns undefined when the undefined itself was not doing the same. In most modern browsers window.undefined is not writable but can be shadowed as its a valid variable name. Well, I wouldn't say its a real case scenario but a foolproof way to return undefined.

function whendefined(){
    var undefined = 'defined';
    return undefined;
}

console.log(whendefined());

function neverdefined(){
    var undefined = 'defined';
    return void 0;
}

console.log(neverdefined());

MDN community docs has something in the same lines too

This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired. The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

The use in the es-lint example is probably having only a file size consideration as these won't be minified in any way.

"undefined".length; //9
"void 0".length;//6

10,000 downloads can save ~30,000 bytes.

Consistent Return has nothing to do with this directly, it just makes sure return values are specified explicitly and consistently. All through the code the consideration for using void 0 seems to be file size consideration and may be some old style coding of author carried over from old browsers where even window.undefined can be overridden.

Sphenic answered 5/6, 2017 at 6:31 Comment(2)
Have a look at my updated question, it has examples of eslint using the operator quite a lot. Maybe it'll help you expand you answer?Branching
I probably only file size consideration, See updated answer.Sphenic
G
2

The above 2 functions are doing the same thing except that the former is written in one line. void is most used in the content of hyperlinks, where the browser may interpret the results of a return and try to display the results.

In your updated code, the void is important, because the author of the function wants to do the following actions in one line.

  1. Perform res.send(foo)
  2. return void (nothing)

Thus he/she uses void to cast the result to undefined

Gaillard answered 5/6, 2017 at 6:27 Comment(0)
W
0

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
Whoop answered 1/8, 2022 at 19:10 Comment(0)
D
0

I have a usecase that I can't find reference to:

overlay.classList.remove('entered');
void overlay.offsetWidth;  // necessary to trigger a one-time animation
overlay.classList.add('entered');

This is a 'trick' that ensures that the browser executes an animation frame, so that the trigger for an animation playing on the .entered class takes effect again.

I can't find reference to it now, so would love to find out which bits are still necessary.

Derinna answered 25/4 at 20:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.