Why is 3 returned?

Tell us what’s happening:
Why is 3 returned? After the if statement i is 2 and will break out of the loop after the return statement

  **Your code so far**
var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;                                                               <- This should break out and return 2
    };
  }
}
console.log(printNumTwo());
  **Your browser information:**

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

Challenge: Compare Scopes of the var and let Keywords

Link to the challenge:

This return statement is part of the function printNumTwo definition. After the if statement, the loop variable i increments to three, the condition i < 3 is false, and the loop terminates.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.