-2

I was wondering in this example if x would become a global variable as if was not declared inside the local function? Will javascript exit the local function, search until it doesnt find an x, and then implicitly create a global x?

function f(){
 var ar=[],i;
 for(i=0;i<3;i++){
//this time instead of passing i, the funciton has a local value called 
x 

arr[i]=(function(x)){
  return function(){
    return x;
  };
}(i));
}
return arr; 
}
akotch
  • 205
  • 3
  • 10
  • 2
    Those are called **IIFE**s (**I**mmediately **I**nvoked **F**unction **E**xpression). It is used here to solve this very famous [**problem**](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – ibrahim mahrir May 28 '18 at 23:24
  • It is a passed argument... the function's definition tells you what it becomes – Patrick Evans May 28 '18 at 23:25
  • 3
    Possible duplicate of [What is the (function() { } )() construct in JavaScript?](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – Nick May 28 '18 at 23:29

1 Answers1

-1

Try running the code below and notice how we added the () for function x. Take those out and notice the difference in the console.log. Your edited question is kinda dumb. Just console.log(x) and see what happens

var WINDOW_PROPS = Object.keys(window);



arr =[]
function f(){
    for(i = 0; i < 3; i++) {       
        arr[i] = (function(x){                               
                  return function (){
                         return x*x;
                  }();
        }(i));
        console.log(arr[i])
    }
    
    var GLOBALS = Object.keys(window)
    // filter the props which your code did not declare
    .filter(prop => WINDOW_PROPS.indexOf(prop) < 0)
    // prettify output a bit :) It's up to you...
    .map(prop => `${typeof window[prop]} ${prop} ${window[prop]}`)
    // sort by types and names to find easier what you need
    .sort();

    console.log(GLOBALS.join("\n"));

    return arr;
    
    
} 

f()
DCR
  • 10,658
  • 7
  • 38
  • 86
  • I dont think you understand the question, this is not my example its from a book. The example works its from a book, but its not a question of what will print, its a question of the scope chain. – akotch May 28 '18 at 23:42
  • what part of your question am I missing? When you console.log(x) your get Uncaught ReferenceError: x is not defined hence it was not made a global variable and is only in scope within the function. I thought it a 'dumb' question as you could easily discover this on your own. I don't think you understood the answer – DCR May 28 '18 at 23:45