Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
return statement in a for looop

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());

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

@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());

about 4 years ago · Juan Pablo Isaza Report

0

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
*/
about 4 years ago · Juan Pablo Isaza Report

0

You have defined the i variable in for loop with the var keyword. var has function scope and due to this when the for loop runs, i will be increased to 3 and then it will check for condition and exit the for loop but it will be assigned value 3 to i in the global scope.

To get 2 as the output you have to define i with the let keyword that has block scope and the last fetched value will be provided when the function runs.

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!