JavaScript: var vs let and which one to use
Like many things in JavaScript, it has quirks to declare variables using the var keyword. var is a function-scoped keyword, so if we define a variable inside the if statement, the variable will be visible outside that scope. Creepy!
function wrong() {
if (true) {
var x = 5;
}
return x;
}
wrong(); // prints 5
If we change it to let, we get a sane result.
function right() {
if (true) {
let x = 5;
}
return x;
}
right(); // Uncaught ReferenceError: x is not defined
So the recommendation is to use the keyword let for declaring variables.