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

236
Views
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 answers
Answer question

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 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!