What is the difference between return and return()?

后端 未结 9 1458
误落风尘
误落风尘 2020-12-13 16:37
function a() { return 1; }
function b() { return(1); }

I tested the above code in Chrome\'s console, and both returned 1.



        
9条回答
  •  死守一世寂寞
    2020-12-13 17:13

    In the return statement, the parentheses around the expression are already built in.

    In JavaScript, as in many other languages (like C, C++, Java, Python), the return statement has two parts: the keyword return and an (optional) expression. So in, any case, all that is following the return keyword is first evaluated as an expression, after that, the return statement is "executed" by passing the control back to the caller.

    To use or not to use parentheses is a matter of style, whereas most style guides forbid them for trivial cases like the one quoted in your question, because it makes return falsely looking like a function.

    Later addendum

    If with parentheses or without, never forget to place the optional expression behind the return, that is, in the same line. The real pitfall with return in JavaScript lies in adding a line break after it:

    function test() {
      return 
      1;
    }
    

    ... because above test function will return undefined.

提交回复
热议问题