Reputation: 261
I am using the latest Firefox (4.0.1) and Firebug (1.7.2).
Any time I enter a variable declaration into the console, an italicized "undefined" warning is returned.
So for example if I enter "var x = 5;" then the response is "undefined", rather than "5".
Afterward if I enter "x" into the console, the proper value of 5 is returned. However the error/warning is a bit of a nuisance, would really like to know the cause and resolution, and if I'm the only one experiencing this.
Interestingly if I don't use "var" but just declare the value using "x=5" then the correct behavior exhibits and "5" is returned in the console.
Upvotes: 5
Views: 1880
Reputation: 11
Unlike some other languages, in JavaScript every piece of code is either an expression or a statement. Expressions always return a value. Statements always return undefined. What is a statement and what is an expression is defined in the original JavaScript specification from 1997.
For example, say this is our program:
var color = "blue";
color = "red";
You will notice that if you enter this line-by-line into your console, the 1st line returns undefined, while the 2nd line returns "red".
This is because, as you may have guessed, a variable declaration (var something = something
) is a statement, whereas a variable assignment (something = something
) is an expression.
If you're curious, try reading through how JavaScript evaluates an assignment in 11.13.1 (page 50), under the "Simple Assignment" section in the spec I linked above.
Upvotes: 1
Reputation: 360
Firebug is reporting the result of evaluating the expression, equivalent to:
typeof eval("var x = 5;");
"undefined"
typeof eval("x = 5;");
"number"
Upvotes: 0
Reputation:
(This is just a guess, I'm not an expert on the details of Javascript's language rules or on Firebug.)
The feedback the console gives you is the result of the evaluation of the line you entered. I assume the declaration var x = ...
is a statement that doesn't have a value, while simple assignment (x = ...
) is, in line with the C heritage and the "everything is an expression" attitude of functional languages, an expression that evaluates to the assigned value.
Upvotes: 4