Old habits die hard. This applies to me when it comes to declaring variables especially when I get in the flow and I am just automatically declaring all variables with var. So the purpose of this article is for me to stop this habit once for all.
Var is function scope. This means when a variable is declared with a var in a function, that variable can’t be accessed outside of that function and it will throw an error.
function sound() {
var dog = "woof"
console.log(dog)
}
sound()
/// woof
woof
/// Uncaught ReferenceError: dog is not defined
However, if a variable is declared with a var in a block scope, that variable can be accessed outside of that block scope.
var sound = "woof"
if (sound === "woof") {
var animal = "dog"
console.log(`${animal} goes ${sound}`)
}
/// dog goes woof
animal
/// "dog"
This problem can be fixed by declaring variables with let, which is block scoped.
var sound = "woof"
if (sound === "woof") {
let animal = "dog"
console.log(`${animal} goes ${sound}`)
}
/// dog goes woof
animal
/// Uncaught ReferenceError: animal is not defined
Const is similar to let but with one big difference. Const can’t be reassigned. Also both const and let can’t be redeclared unlike var.
Top comments (0)