Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda