|
|
|
|
|
by Meegul
3530 days ago
|
|
It's spelled out pretty well in the article. But if you want another example, consider these two code blocks: var foo;
var bar;
{
let foo = "hello";
var bar = "world";
}
console.log(foo);
console.log(bar);
This produces: undefined
world
The reason being that the `let` statement restricted that variable to the block it was in (defined by the { and }). `var` declares the variable globally, allowing it to be accessed outside of the {}.We prefer now to use `let` and `const` over `var` because it doesn't pollute the global namespace. With the asynchronous nature of Javascript, it's theoretically possible for you to declare a variable with `var`, assign it a value, then immediately use that value and find that it's different than what you expected because of another function using the same variable name. This isn't possible with `let`. |
|
Not quite. var's are hoisted to the top of their most local function.
The above code essentially gets translated to the following: