undefined thrown when defining var

后端 未结 2 836
萌比男神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: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.)

提交回复
热议问题