1
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 baras 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

Cœur
  • 37,241
  • 25
  • 195
  • 267
MrMangado
  • 993
  • 4
  • 10
  • 26

2 Answers2

5

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?

Community
  • 1
  • 1
GSerg
  • 76,472
  • 17
  • 159
  • 346
1

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);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758