What are the differences between let and var in JavaScript? Explain with examples
Hello! I started learning JavaScript and encountered some confusion. I know that previously everyone declared variables using `var`, but now modern tutorials recommend `let`. They seem to do the same thing — create variables. But when I write code, they behave differently.
Here's an example that confused me:
```javascript
var x = 10;
if (true) {
var x = 20; // I thought this was a new variable
console.log(x); // 20
}
console.log(x); // 20 — why not 10?
```
If I replace `var` with `let`:
```javascript
let x = 10;
if (true) {
let x = 20;
console.log(x); // 20
}
console.log(x); // 10 — and here it's 10, as expected
```
Why does this happen? And I also heard about "hoisting" — is that related somehow? Please explain for a beginner when to use
No answers yet.
Log in to leave an answer
Blogs