Take the 2-minute tour ×

I'm reading this article and there is a paragraph:

If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:

 (function() {
        var myProperty = "hello world";
 alert(typeof(myProperty)); // undefined

I met with this already but still need some clarification why should I need to explicitly scope a variable inside a function when variables are implicitly scoped inside a function in Javascript.

Could you explain the purpose of this?

thank you

share|improve this question
maybe because you don't want to overwrite the value of a global variable? –  Achshar Sep 13 '11 at 12:49
@Achshar Yes, but I couldn't imagine this situation. Raynos example opened my eyes. –  xralf Sep 13 '11 at 12:59
add comment

1 Answer

up vote 3 down vote accepted
  setTimeout(function() { console.log(i) }, 10);

// alerts 10, 10 times

  (function(i) {
    // explicitly scope i
    setTimout(function() { console.log(i) }, 10);

When generating functions inside other functions and accessing variables up the scope chain through closure scope it may be useful to "explicitly scope" a variable inside the outer function.

Although this is an anti pattern. The correct solution would be

var generateLogger = function(i) {
  return function() { console.log(i); };

  setTimeout(generateLogger(i), 10);

Since generating functions in a loop is inefficient and bad practice.

There are no real use cases of "explicitly scoping" variables that can't be avoided by not creating functions inside other functions.

share|improve this answer
Thank you for answering the OP's question and providing an actual example –  gladsocc Sep 13 '11 at 12:39
@Raynos : Thank you, now it's clear. There is only one strange thing. The output in the first example is (54, 10, ... 10) and (undefined, 0, ..., 9). Why there is one more extra value? and why in the first case it isn't (54, 0, ..., 0), the last value of i overwrites the preceding values? –  xralf Sep 13 '11 at 12:56
@xralf the 54 and undefined are the value of executing the "expression" that is the for loop in the console. 54 is the return value of the last setTimeout and undefined i the return value of the anonymous function. –  Raynos Sep 13 '11 at 13:26
@xralf in the first example it's 10, ... 10 because the setTimeout function prints the current value of i after 10 milliseconds. the current value of i is 10 when those functions execute. –  Raynos Sep 13 '11 at 13:27
@Raynos This could be a bug in the future when the for loop should execute 10 times but it executes 11 times, it's good to know this pitfall. –  xralf Sep 13 '11 at 13:58
show 2 more comments

Your Answer


