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

238
Vistas
Why does a For Loop still work without proper initialisation?

If I omit the 'let' or 'var' from a javascript for-loop, it still works. So instead of declaring "let i = 0" in the loop and just typing "i = 0" it still seems to have the same scope and works the same. Why is that?

How can the "i++" part work without knowing what type it is and without knowing its start value?

This code still executes properly:


<p id="demo"></p>
<p id="i"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

let text = "";
let iter = "";
for (i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
  iter = i;
}

document.getElementById("demo").innerHTML = text;
document.getElementById("i").innerHTML = iter;
</script>```
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In JavaScript, if you omit the "var", "let" or "const" keyword during a variable initialization, it will be initialized as a GLOBAL variable.

Your "i" variable will be visible outside the for loop. The loop works, of course since it IS initialized properly, but be aware of all the drawbacks of declaring global variables.

Just to have a better clue, you can try to manipulate this "i" variable outside the for loop, or just using a

console.log(i)

In other words declaring a variable (let's call it "index") without using "var", "let" or "const" it will be equivalent of declaring it as

window.index = 0;
//100% equivalent to
index = 0;

EDIT: an exception I didn't mention is the case you use the "strict mode" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

In this case it will throw an exception as you would initially expect. To declare variables in strict mode you have to use "let", "var" or "const" keywords.

If you use the strict mode, the only way to declare global variables is through window Object

window.yourNewGlobalVariable = 'whatever' //works in strict mode
yourNewGlobalVariable = 'whatever' // doesn't work in strict mode
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