In chrome Developer tools, when I type
a = 3 logs 3 but
var a = 3 logs undefined.
Why does the first statement return 3 but not the second one?
In chrome Developer tools, when I type
a = 3 logs 3 but
var a = 3 logs undefined.
Why does the first statement return 3 but not the second one?
Because that's the way it is.
A statement beginning var
is a declaration. Declarations don't, in and of themselves, have a value. They tell the computer to do something (to create a variable, optionally with some initial value).
But assignment expressions are different. a = b
evaluates to (or "has") the new value of a
, in order to allow chaining, such as a = b = c = d
.
Could they have made it so that var a = b
was an expression and evaluated to something? Sure, probably. But it would hold absolutely no useful value to butcher the language grammar in such a manner.
Read up about statements and expressions in programming languages.
Because undefined
is the result of the var
statement.
Statements don't actually have a "result" that can be used in your code, but a program has a final result, and your single line of code in the console is evaluated as a program.