Home > Software engineering >  return statement in a for looop
return statement in a for looop

Time:12-31

It is said that "RETURN" statement terminates a for loop in javascript but in this case the code will still output 3 why? does that mean the return statement doesn't terminate the loop?

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

CodePudding user response:

@jeremy-thille explained how the loop continues and i becomes 3. Additionally, this occurs, because i is not scoped within the loop. If you use let to assign i, it is scoped within the loop (block-scoped), and the result would be as expected.

let printNumTwo;
for (let i = 0; i < 3; i  = 1) {
  if (i === 2) {
    printNumTwo = () => i;
  }
}

console.log(printNumTwo());

CodePudding user response:

You can add console.log to understand. Since, printNumTwo = function(){} is definition of function not execution. You can try other example:

var printNumTwo;
for (var i = 0; i < 3; i  ) {
  console.log('before', i);
   printNumTwo = function() {
      console.log('end', i);
      return i;
    };
  if (i === 2) {
    console.log('process', i);
  };
  console.log('after', i);
}
console.log(printNumTwo());
/* ouput
> "before" 0
> "after" 0
> "before" 1
> "after" 1
> "before" 2
> "process" 2
> "after" 2
> "end" 3
> 3
*/

CodePudding user response:

var printNumTwo;
for (let i = 0; i < 3; i  ) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    } 
  }
}
 console.log(printNumTwo()); 
you have defined i variable in for loop with var and it has a function scope and due to this when for loop runs i will be increased to 3 and then it will check for condition and exit the forr loop but it will be assigned value 3 to i in global scope so to get two as output you have to define i with let and it has block scope and last fetched value will be provided when function runs.

  • Related