I'm having a problem understanding why name is getting a value here
(function() {
(function() {
var name = 'Fido';
})();
})();
console.log(name + ' says woof'); //Output: Fido says woof
Shouldn't the variable name be local to the internal function?
-
The variable is local to the inner function. I can't reproduce your result.nnnnnn– nnnnnn2013年11月27日 00:18:06 +00:00Commented Nov 27, 2013 at 0:18
-
So my console says "Fido says woof". It should say something like "undefined says woof"planetoftheweb– planetoftheweb2013年11月27日 00:24:55 +00:00Commented Nov 27, 2013 at 0:24
2 Answers 2
The variable is local, and the value that you see doesn't come from the assignment inside the function.
You have named your window "Fido" also, and when you use name in the global scope, you get the window.name property.
If you try it in a jsfiddle, you will get "result says woof".
2 Comments
You are wrong! If executed in browser console this code will output:
says woof
I think you need to understand hoisting better. This article is definitely going to help you. Here is a short description taken from the article:
In JavaScript, a name enters a scope in one of four basic ways:
- Language-defined: All scopes are, by default, given the names this and arguments.
- Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
- Function declarations: These are of the form function foo() {}.
- Variable declarations: These take the form var foo;.
Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there. This means that code like this:
function foo() {
bar();
var x = 1;
}
is actually interpreted like this:
function foo() {
var x;
bar();
x = 1;
}
It turns out that it doesn’t matter whether the line that contains the declaration would ever be executed. The following two functions are equivalent:
function foo() {
if (false) {
var x = 1;
}
return;
var y = 1;
}
function foo() {
var x, y;
if (false) {
x = 1;
}
return;
y = 1;
}
6 Comments
Explore related questions
See similar questions with these tags.