Why does void in Javascript require an argument?

后端 未结 2 552
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 18:48

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

相关标签:
2条回答
  • 2021-01-11 19:12

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

    0 讨论(0)
  • 2021-01-11 19:36

    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.

    0 讨论(0)
提交回复
热议问题