Why does void in Javascript require an argument?

From what I understand, the void keyword in Javascript is some kind of function that takes a single argument and always returns undefined . For some reason you need to pass an argument; he will not work without him.

Is there a reason why this argument is required for this?

What's the point? Why this will not work without an argument. The only thing I saw for this is to get the result undefined . Are there any other options for this?

If not, then it would seem that the requirement for the transmitted expression would be meaningless.

+7
javascript void
source share
2 answers

According to this page https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void void is an operator that simply returns undefined after evaluating the expression that you pass to it, The operator needs operand to work. That is why the parameter is passed.

 console.log(void true); console.log(void 0); console.log(void "Welcome"); console.log(void(true)); console.log(void(0)); console.log(void("Welcome")); 

All of these statements will print undefined

 var a = 1, b = 2; void(a = a + b) console.log(a); 

And it will print 3 . Thus, it is obvious that he appreciates the expressions that we pass on to him.

Edit: As I find out from this answer, https://stackoverflow.com/a/4646263

undefined is just a global property that can be written to. For example,

 console.log(undefined); var undefined = 1; console.log(undefined); 

He is typing

 undefined 1 

So, if you want to absolutely make sure that undefined used, you can use the void operator. Since this is an operator, it cannot be overridden in javascript.

+6
source share

void also evaluates the expression you pass to it. It does not just return undefined .

+2
source share

All Articles