Why the function under the if-condition excites. even if the if condition is satisfied

as we learn. under the ( IF- condition) topics, the function under the IF- CONDITION is executed if and only if the IF-CONDITION is satisfied. but now I will face some coding style under ES6 that fails the if- condition rule.

Here The function under the IF-CONDITION is executed even if the if condition. is not satisfied

 var printNumTwo;

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

The out-put of these code is ,3 whe i run, but 3 is not sastified the if condition, the if condition says IF(I===2)

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

the code inside the loop execute multiple times, with different values of i, the if statement execute only the time in which i has value of 2

try running it like this:


 var printNumTwo;

for (var i = 0; i < 3; i++) 
{
console.log("the value of i is " + i);
  if (i === 2) 
     {
      console.log("the if statement execute (i has value of 2)")
         console.log("the function is defined when i has value of " + i)
    printNumTwo = function() 
            {
                console.log("the function run when i has value of " + i);
                                     return i;
          };
  }
}
console.log("after the loop i has value of " + i);
console.log(printNumTwo());

the function run when i has value of 3
but 3 doesn’t full fill The if condition. and the function is inside the if- condition

this is the thing it wants to show:
the variables defined with var are function scoped, in this case the i variable is not defined inside a function, so it is global scoped.
the function will print the value that i has when it is called, not when it is defined.

same behaviour you could have with

var count = 0;
function printCount() {console.log(count)};
count++;
printCount(); // print 1
count++;
printCount(); // print 2

it is complex like this, to see the difference with variables declared with let in loops

1 Like