I didn't understand the exercise where the function is used inside the for loop

Tell us what’s happening:

Your code so far


var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 3

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36.

Challenge: Compare Scopes of the var and let Keywords

Link to the challenge:

@nikhilgangeri What specifically do you not understand?

1 Like

i couldn’t evaluate how the function is working inside the for loop. the function specified inside the for loop doesn’t have a name and the function called in the console.log, which function is it referring to?

The function inside the for loop does have a name. It is printNumTwo. The variable printNumTwo is assigned an anonymous function once the variable i is equal to 2.

1 Like

So does it mean that assigning the variable printNumTwo with an anonymous function does give that function a name.

Kind of. It is considered a function expression vs. function declaration. Technically, the function is anonymous. But if you call printNum, it will be the same as if it would have been declared as:

function printNumTwo() {
      return i;
    };

In fact, I can give the function a name (i.e. someFunction) and it will still work the same.

var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function someFunction() {
      return i;
    };
  }
}
console.log(printNumTwo()); // 3
1 Like

@aaroncompaniados722 Please don’t just copy/paste the hints from the Guide. Users can view those anytime. Try to answer the question posted, which was not how to solve the challenge.

Oh yeah. thanx for the help. Didn’t knew the concept of anonymous function and function expression before. Now i’ve understood. Just a small doubt, do we need to type ‘use strict’; everytime we use let keyword. If so why?