# Function inside for loop

**URL:** <https://forum.freecodecamp.org/t/function-inside-for-loop/195973>\
**Category:** Curriculum Help\
**Tags:** javascript\
**Created:** [June 3, 2018, 2:15pm UTC](https://forum.freecodecamp.org/t/function-inside-for-loop/195973 "2018-06-03T14:15:19Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![ridafatima15h1](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ridafatima15h1/32/101179_2.png) [@ridafatima15h1](https://forum.freecodecamp.org/u/ridafatima15h1)\
**Post date:** [June 3, 2018, 2:15pm UTC](https://forum.freecodecamp.org/t/function-inside-for-loop/195973/1 "2018-06-03T14:15:19Z")

</div>

hi  
can anyone explain why variable “i” updates to 3 inside the function in the third iteration of the for loop i-e when i =2.

```auto
var printNumTwo;
for (var i = 0; i < 3; i++) {
  console.log("i1: ",i);
  if(i === 2){
    console.log("i2: ",i);
    printNumTwo = function() {
      console.log("i3: ",i);
      return i;
    };
  }
}
console.log("ans: ",printNumTwo());
// returns 3

```

see this link please to run the code:  
[link](https://repl.it/repls/ConcernedNiftyButtons)

thanks all in advance!

---

<div class="post-metadata">

**Author:** ![alhazen1](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/alhazen1/32/85244_2.png) [@alhazen1](https://forum.freecodecamp.org/u/alhazen1)\
**Post date:** [June 3, 2018, 5:18pm UTC](https://forum.freecodecamp.org/t/function-inside-for-loop/195973/3 "2018-06-03T17:18:44Z")

</div>

Generally declaring functions in loops is a problem. Most linters will flag it with a warning.

Your function will always return whatever the current value of i is at the time you invoke it. By using var to declare i it is available globally. Add a line to your code `i=23;` and your function will return 23.

Why 3? Your i increments by one. When it becomes three the test condition becomes false and your loop ends. At the end of your loop i did equal 3.

If you use let to declare i then you will have created a closure and your function will work as expected. That particular i will not be available globally but will live on after your block goes out of scope because it is used in your function. I would suggest finding a good tutorial or article on closures - it is a thick subject and I’m no expert.

```javascript
var printNumTwo;
for (var i = 0; i < 3; i++) {
  console.log("i1: ",i);
  if(i === 2){
    console.log("i2: ",i);
    printNumTwo = function() {
      console.log("i3: ",i);
      return i;
    };
  }
}

i = 23; // read up on polluting global namespace
// we use i a lot in loops so this could be a problem
console.log("ans: ",printNumTwo());
// returns 23 !!!!!!!!!!!!!!!

```

---

<div class="post-metadata">

**Author:** ![JM-Mendez](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/jm-mendez/32/33681_2.png) [@JM-Mendez](https://forum.freecodecamp.org/u/JM-Mendez)\
**Post date:** [June 3, 2018, 5:20pm UTC](https://forum.freecodecamp.org/t/function-inside-for-loop/195973/4 "2018-06-03T17:20:53Z")

</div>

This is due to closures. Essentially in javascript, unlike other languages, functions have access to anything in their scope after they return.

So what happens when you use `var` is that the variable is bound to the global scope, and every function has access to it. When we finally call `printNumTwo`, it still can only access the global `i` at the moment you call it, which will be 3, since the loop ends when it reaches 3.

I find it helps me to walk through how the js engine runs this code, line by line.

1. assign variable `printNumTwo` to the global scope (since you’re using `var`)
2. enter the for loop and assign the global variable `i` and set it to 0
3. run the for loop and `console.log` every value for `i`
4. if `i === 2 console.log`
5. if `i === 2` assign `printNumTwo` to the inner function
6. store a reference to the global variable `i` inside `printNumTwo`
7. exit the loop when the global `i === 3`
8. `console.log("ans: ",printNumTwo())` the current value of `i`

At step 8 the the value of the global `i` is 3, and the reference inside `printNumTwo` is mutated (changed). So that’s what gets logged.

Using es6 this is easily solved by using `let` whenever you intend to reassign a variable. `let` is bound to the function scope that sets it. Therefore step 6 changes and instead does

- store a reference to the local variable `i` in the inner function (which is equal to 2 at this point)

Then at step 8, `printNumTwo` has access to the value of `i` when it was assigned.

Hope that helps. Closures take a while to understand sometimes.

---

<div class="post-metadata">

**Author:** ![ridafatima15h1](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ridafatima15h1/32/101179_2.png) [@ridafatima15h1](https://forum.freecodecamp.org/u/ridafatima15h1)\
**Post date:** [June 3, 2018, 7:11pm UTC](https://forum.freecodecamp.org/t/function-inside-for-loop/195973/5 "2018-06-03T19:11:47Z")

</div>

@alhazen1 @JM-Mendez thank you so much for the needed help and clear elaboration !

---

<div class="post-metadata">

**Author:** ![ILM](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ilm/32/363239_2.png) [@ILM](https://forum.freecodecamp.org/u/ILM)\
**Post date:** [January 17, 2021, 7:30am UTC](https://forum.freecodecamp.org/t/function-inside-for-loop/195973/6 "2021-01-17T07:30:27Z")

</div>

Closed on January 17, 2021, 7:30am UTC


