Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was reading the 'learning Node' book and I was stuck in a very simple issue, one that I haven't given too much thought about: assignment in javascript.

The author states that we should realize that by using the Node's REPL, the following would return undefined:

var a = 2
(undefined)

while the code below will return '2' in the REPL:

a = 2
2

why is that? the code right above is not an attribution? how come? If the var 'a' hasn't existed until that point in the code, how come it is not and attribution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
351 views
Welcome To Ask or Share your Answers For Others

1 Answer

Per ECMA-262 § 12.2, a VariableStatement (that is, var identifier=value) explicitly returns nothing. Additionally, a VariableStatement is a Statement; Statements do not return values, and it is invalid to put a Statement somewhere an Expression would go.

For example, none of the following make sense because they put a Statement where you need value-yielding Expressions:

var a = var b;
function fn() { return var x; }

Per § 11.13.1, assignment to a variable (identifier=value) returns the assigned value.


When you write var a = 1;, it declares a and initalizes its value to 1. Because this is a VariableStatement, it returns nothing, and the REPL prints undefined.

a=1 is an expression that assigns 1 to a. Since there is no a, JavaScript implicitly creates a global a in normal code (but would throw a ReferenceError in strict mode, since you're not allowed to implicitly create new globals in strict mode).

Regardless of whether or not a existed before, the expression still returns the assigned value, 1, so the REPL prints that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...