tags:

views:

43

answers:

3

When I run "var variable = true;" in chrome console I get "undefined" returned:

> var variable = true;
undefined

But when I run without "var" it returns true:

> variable = true;
true

Why is it returning "undefined" with "var"?

It's confusing cause I expected it would return true.

+4  A: 

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);
Marcelo Cantos
Is it valid js code to use "var variable = true;" or should i run "var variable; variable = true;"?
never_had_a_name
@ajsie - it is valid, and both statements are equivalent.
Oded
Yes, it is valid code. You can confirm this by evaluating `variable` after executing the statement.
Marcelo Cantos
+1  A: 

An assignation returns the assignation's value, but with var this return is "consumed" (?)

MatTheCat
+2  A: 

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.

KennyTM