Reputation: 993
function foo() {
var bar = 'no'
setInterval(function() { console.log(bar); }, 1000);
}
When I execute this piece of code, I got the following output: no
, so the output is correct. But when I execute the next piece of code, when I pass the function bar
as a parameter to that anonymous function, I don't know exactly why the output is undefined
function foo() {
var bar = 'no'
setInterval(function(bar) { console.log(bar); }, 1000);
}
If I pass the variable as a parameter, why is undefined? If there was also a variable call bar
inside the anonymous function, I know that variable would be rewritten with the inner function value, but I can't understand this behavior
Upvotes: 1
Views: 157
Reputation: 78155
In your first example you create a closure -- the function you create is linked to the bar
variable. It is not passed to the function as a parameter. When setInterval
later calls the function without providing any parameters, it works as expected because the function has closed over bar
variable.
In your second example you don't pass the variable as a parameter. You describe a function that accepts one parameter, and is not closed over anything. Then later setInterval
calls that function in the same way, providing no parameters. If a parameter is not provided in javascript, it becomes undefined
.
(You can call a function in js with any number of parameters, regardless what parameters the function is declared with).
More reading about closures: How do JavaScript closures work?
Upvotes: 5
Reputation: 382102
When the callback is called, it is called without parameters by setInterval, so the argument bar
, which shadows the external bar
, is undefined
.
You can pass the parameter as argument of setInterval
:
setInterval(function(bar) { console.log(bar); }, 1000, bar);
Upvotes: 1