Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 636
borislemke Avatar asked Oct 17 '22 11:10

borislemke


1 Answers

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

like image 173
Alexios Tsiaparas Avatar answered Oct 21 '22 07:10

Alexios Tsiaparas