Value returned by the assignment

前端 未结 5 1635
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 04:32

Why does the regular assignment statement (say, x = 5) return the value assigned (5 in this case), while the assignment combined with a variable d

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 04:56

    That's the way the language was designed. It is consistent with most languages.

    Having a variable declaration return anything other than undefined is meaningless, because you can't ever use the var keyword in an expression context.

    Having assignment be an expression not a statement is useful when you want to set many variable to the same value at once:

    x = y = z = 2;
    

    It can also be used like this:

    x = 2*(y = z); // Set y = z, and x = 2*z
    

    However that is not the most readable code and it would probably be better written as:

    y = z;
    x = 2*z;
    

提交回复
热议问题