I'm very new I dont know what the problem can possibly be. Code
for (let i = 0; i < 5; i++) {
console.log("Inside the loop:", i);
}
console.log("Outside the loop:", i);
This is what it prints,
Inside the loop: Inside the loop: Inside the loop: Inside the loop: Inside the loop:
I am trying to find the difference between let and var, but if you can, I don't really want a too complex sentence, as I probably wont understand, anything.
When you use let i = 0 inside a for loop, the scope of the variable i is limited to only the for loop. You can only use this variable inside there. Outside the for loop, this variable is undefined. If you want to use this variable outside the for loop, you should use var instead of let.
[EDIT]: It is important to note that it is highly NOT RECOMMENDED and not a good coding practice to use global variables. With that in mind, avoid using var whenever it is possible.
Take a look here: var keyword
And here: let keyword
You would need to define the variable i outside of the loop. The way you have it, the variable is only active inside the for loop. You'll need to give it a value as the outside statement requires one.
var i = 0;
for (i = 0; i < 5; i++) {
console.log("Inside the loop:", i);
}
console.log("Outside the loop:", i);
The difference between var and let/const is scope.
If you use var, you can declare it inside the loop (inside the for statement) and it will work outside the loop as well. var always has global scope:
for (var i = 0; i < 5; i++) {
console.log("Inside the loop:", i);
}
console.log("Outside the loop:", i);
If you use let inside the for loop, as you see, the statement outside the loop doesn't recognize it. let (or const) only has local scope (i.e. inside the function, loop, or braces in which it is declared):
let i
for (i = 0; i < 5; i++) {
console.log("Inside the loop:", i);
}
console.log("Outside the loop:", i);