What does function() do?

I tried to look this up but idk what is happening or what this is actually called.

'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
   printNumTwo = function()
     return i;
   };
  }
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns "i is not defined"

Also in this case i is returning 2, and if “strict” and let is not used i returns 3. Would this be the case if printNumTwo = i and then used in console.log?

I guess the main question is what is function() doing and what is the difference between calling printNumTwo when function() is used, compared to printNumTwo when it is set to a value and called?

Thanks for any insight.

The second part of your question, that is, “i is not defined”,for that you need to read about variable scopes. There are mainly two types of scopes: global and local. In this case, i is local to the scope of for loop. That means it is just available for the for-loop and as soon as the loop ends, the variable “i” is no longer accessible by the program.

The first part of your question in which you have declared a function within the for-loop and calling that function is a bit something new for me and interesting. I have never seen something like this before.

Okay. So I found out a similar issue solved by someone in FCC forum. Let me share the link.

Cool thanks for the replay.

I went back and read the tutorial and I missed where it said that var was a global variable. I thought that it was similar to C and would only be global if declared a certain way or in a certain area of code. That isn’t the case.

let is the local version. So even if a counter is called in a loop with var it will be global.

I have been able to find a few things on function(). It is called anonymous function I believe.

Here is a link: https ://en.wikibooks.org/wiki/JavaScript/Anonymous_functions

I believe it sets printNumTwo to an unnamed function. Only thing now is I don’t know if when called if printNumTwo() is equal to i or if it is simply a function now that only returns i. I guessing the latter but I still don’t know enough js to know for sure.

1 Like

It’s called a closure (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)
because the function closes around the variable, so the variable is within its scope, even when its not in the scope of where the function is being called from.