0

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 `123`.
Hernan
  • 1,149
  • 1
  • 11
  • 29
  • 1
    I believe this question has been answered here: http://stackoverflow.com/questions/22844840/why-does-javascript-variable-declaration-at-console-results-in-undefined-being – aaron-prindle Sep 03 '15 at 17:02

2 Answers2

2

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    Actually, the statement (no pun) "statements have no value" isn't correct for JavaScript (which I was very surprised to learn a few months back). Try this in your console, for instance: `{1, 2, 3}`. The result is `3`, because [the result of a block statement is the value of the last statement within the block](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-block-runtime-semantics-evaluation). – T.J. Crowder Sep 03 '15 at 17:04
2

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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875