Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda