The code does not say ‘return i if i is 2’. The code says ‘define the function printNumTwo if i is 2’. But var will hosit the declaration outside of the scope where it was defined use the same variablei for the entire function scope. (Edit because @chuckadams descption is more accurate. I was getting it a bit mixed up) When printNumTwo is called, i was already incremented to 3.
When you use var foo, then there is only one foo variable for the entire function, whether it’s part of a loop or not. Every one of those functions shares the same variable. When you use let, it creates a new variable each time through the loop, so each instance of that inner function gets a fresh copy.
Creating functions like this in a loop is something you normally Would Never Do, but it does sometimes happen accidentally, when creating a bunch of event handlers for instance. The solution is pretty simple: never use var, always use const and let instead.
The code does not stop running at the if statement in either case.
This is what’s going on. The code continues to run, but the printNumTwo function retained the version of i set to 2 instead of the incremented quantity like with var.