0

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.

Sphinx
  • 10,519
  • 2
  • 27
  • 45

4 Answers4

0

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

  • Oh, thanks! I also have another question of can you use the var keyword through many like you know scripts. Like in one script you define apple, like var apple = 5; but then can you use the var apple in another script, so you dont have to type it again in the script, or is var only available in that script, also is this true for const? Thanks! – Beginnertojavascript Oct 19 '21 at 01:00
  • `var` is global, so it can be declared inside the loop and called outside – symlink Oct 19 '21 at 01:08
0

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);
  • You don't need to declare `var` outside of the loop, only `const` and `let`. `var` always has global scope. – symlink Oct 19 '21 at 01:10
0

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);
symlink
  • 11,984
  • 7
  • 29
  • 50
-2

try this

for (let i = 0; i < 5; i++) {
    console.log("Inside the loop: " + i);
}

console.log("Outside the loop:" + i);
f2asr
  • 1
  • 3