"var variable" returns undefined?

The first is a statement, while the second is an expression. While not quite the same, it is similar to C's rules:

// A statement that has no value.
int x = 5;

// An expression...
x = 10;

// ...that can be passed around.
printf("%d\n", x = 15);

var x = y; is a statement which returns no value. In the WebKit JS console, a statement that returns no value will show undefined as the result, e.g.

> if(1){}
undefined
> ;
undefined
> if(1){4}  // this statement returns values!
4

The assignment is an expression which returns the value of the LHS. That means, this expression statement has a return value, and this will be shown.

Tags:

Javascript