undefined thrown when defining var

后端 未结 2 837
萌比男神i
萌比男神i 2021-01-28 22:25

The next code is interpreted in Google-chrome console:

a = 123
123
     % Ok!

var b = 123
undefined
     % `undefined`? why? b is not undefined, it contains `12         


        
相关标签:
2条回答
  • 2021-01-28 22:50

    var is a statement. Statements have no value, so eval() (which the console calls) returns undefined.

    a = 123 is a simple expression, which returns 123 (so that you can write b = a = 123). When passed an expression, eval() returns the expression's value.

    0 讨论(0)
  • 2021-01-28 22:56

    I take it you're doing this in a console that shows you the result of the operation.

    The result of an assignment expression is the value that was assigned. But var statements don't have a result, not least because they don't occur within the usual step-by-step flow of code. We can see this in the definition of the var statement in the spec: §13.3.2.4 tells us that the result of var is the abstract specification call NormalCompletion(empty), which is just an alias for Completion{[[type]]: normal, [[value]]: argument, [[target]]:empty} which is for indicating how a statement/expression completed. In this case, it completes with no value. (Which isn't true of all JavaScript statements, surprisingly.)

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