What is the difference between let and var in JavaScript?
Hi everyone! I just started learning JavaScript and encountered a situation I don't understand. When I declare variables using `var` and `let`, the code behaves differently, and I can't figure out why.
Here's an example that confused me:
```javascript
function test() {
if (true) {
var x = 10;
let y = 20;
}
console.log(x); // 10
console.log(y); // ReferenceError: y is not defined
}
```
Why is `x` accessible outside the `if` block, but `y` is not? I thought both variables were declared in the same place.
Another example with a loop:
```javascript
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// Outputs: 3 3 3
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 1000);
}
// Outputs: 0 1 2
```
Why does
No answers yet.
Log in to leave an answer
Blogs