"var variable" returns undefined?
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.
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.
An assignation returns the assignation's value, but with var
this return is "consumed" (?)
Statements always return undefined
.
var color = "red";
undefined
Expressions always return a value.
color = "orange";
"orange"
I'd like to point out, that the answer provided by kennytm should be the accepted answer, at least for pedagogical purposes. The accepted answer doesn't answer why this is the case or provide deeper understanding.
Like the null
value in JavaScript, undefined
indicates absence of value, but in a much deeper way. The following should be taken as complimentary to the above-mentioned answers:
undefined
is the value of variables that haven't been initialized and the value you get when you query the value of an object property or array element that doesn't exist. This value is also returned by functions that have no return value, and the value of function parameters for which no argument is supplied.undefined
is a predefined global variable (not a language keyword like null) that is initialized to the undefined value.You might consider
undefined
to represent a system-level, unexpected, or error-like absence of value andnull
to represent program-level, normal, or expected absence of value.-- Flanagan, David. JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides) . O'Reilly Media. Kindle Edition.
Also, makes sure to check out both the accepted and the second most voted answer for further reference: Chrome/Firefox console.log always appends a line saying undefined
精彩评论