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