Variable scope in JavaScript: var, let, const and functions
Hello everyone! I just started learning JavaScript and I can't figure out variable scope. I'm writing simple code, but the results keep surprising me.
Here's an example:
```javascript
var x = 10;
function test() {
var x = 20;
if (true) {
var x = 30;
console.log(x); // outputs 30
}
console.log(x); // outputs 30, not 20!
}
test();
console.log(x); // outputs 10
```
Why does the variable `x` change inside the `test()` function, even though I declared it with `var` inside the `if` block? I thought `var` was function-scoped, but here it behaves strangely. I've also heard about `let` and `const`, but I don't understand how they differ.
Another example with closures:
```javascript
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.l
No answers yet.
Log in to leave an answer
Blogs