Reputation: 31
I understand why the following alert() returns "blue".
var color = "blue";
function getcolor () {
return color;
color = "red";
}
alert(getcolor());
If i'm not incorrect, the function stops executing after its return statement, preventing the global "color" variable from being overwritten.
But why, if we change the function's definition to that below, does the alert() return "undefined"?
var color = “blue”;
function getcolor () {
return color;
var color = “red”;
}
alert(getcolor());
I expected that the getcolor() function would exit after the return statement, as before, and return the value of the global color variable "blue".
Upvotes: 2
Views: 76
Reputation: 181027
Local variables are - no matter where the actual var statement is in a function - created at the start of the function. Your latter code translates to something like;
var color = “blue”;
function getcolor () {
var color;
return color;
color = “red”;
}
alert(getcolor());
which shows more clearly why you're getting the effect you're getting.
Upvotes: 2
Reputation: 4209
var statements are executed at the point of entering the function, no matter how deep in the code the actual statement is. So the actual code is:
var color = "blue";
function getcolor ()
{
var color;
return color;
color = "red";
}
alert(getcolor());
It's assingment statement that's never executed, not variable declaration. And you're returning local variable which is yet undefined.
Upvotes: 0