var foo = function bar(i) {
bar = "change bar reference";
if (i < 5) {
setTimeout(function () {
console.log(i);
bar(++i);
},
1000
);
}
}
No errors for the above function.
var foo = function bar(i) {
var bar = "change bar reference";
if (i < 5) {
setTimeout(function () {
console.log(i);
bar(++i);
},
1000
);
}
}
Error on the second function after adding in var to bar.
I expected both of the functions to throw an exception not just the second function with var bar.
I don't understand why only the second function throws an exception.
I get that the variable declaration with var will not overwrite the identifier "bar" but the assignment will do it at run time. I understand why var bar is a string not a function on the second function therefore throws an exception.
Why doesn't the first function throw exception? bar is clearly assigned to a string.
I read the documentation and got something below that might be useful.
The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.
Does "the Identifier in a FunctionExpression cannot be referenced from" mean I can not do bar = "change bar reference"; in the 1st function?
What does the JavaScript script engine do when it sees bar = "change bar reference"? Does it just skip the line?
Edit: Uncaught TypeError: bar is not a function
foo(1)
barto a string, thats why you see the error.baron the global scope,.. But you also havebarin local scope, and that will been seen first.. In the second one your creating both in local scope. If you changed the first one to saywindow.barit will become more obvious what you have done.baron global scope.baris the identifier from the named function expression which can only be accessed inside the function. That is what make the problem interesting.