Why does void in Javascript require an argument?

巧了我就是萌 提交于 2019-12-30 08:11:27

问题


From what I understand, the keyword void in Javascript is some kind of function that takes one argument and always returns the undefined value. For some reason you need to pass it an argument; it won't work without one.

Is there any reason why it requires this argument?

What is the point? Why won't it work without an argument. The only use I have seen for it is to produce an undefined result. Are there any other uses for it?

If not then it would seem that the requirement for an expression to be passed would be pointless.


回答1:


As per this page https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void void is an operator, which simply returns undefined, after evaluating the expression you pass to it. An operator needs an operand to operate on. That is why pass a parameter.

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 these statements would print undefined

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

And this would print 3. So, it is evident that, it evaluates the expressions we pass to it.

Edit: As I learn from this answer https://stackoverflow.com/a/7452352/1903116

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

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

It prints

undefined
1

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




回答2:


void also evaluates the expression you pass to it. It doesn't just return undefined.



来源:https://stackoverflow.com/questions/19367589/why-does-void-in-javascript-require-an-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!