Const, Let and Var
I like to imagine variables like they were drawers with labels. They are used to store data. There are three ways of declaring a variable in JavaScript: var, let or const.
Scope
The scope is the portion of code where the variable is visible. In JavaScript, every function has a scope.
var
Until ES2015 spec, this was the only way of declaring a variable in JavaScript.
var cat = āmeawā
var
allows one to āredeclareā the same variable infinite time, always overwriting the previews declaration:
var cat = āmeawā
console.log(cat) // meaw
var cat = āoof oofā
console.log(gato) // oof oof
let
let
works almost the same way as var
, but it uses the local scope, not global. That means that if the variable is declared using let
inside a function, for example, it will not be available outside that function. The same goes for blocks like if
, for
, while
, etc...
function bark() {
let dog = āoof oofā
console.log(dog)
}
latir() // oof oof
console.log(dog) // ReferenceError: Can't find variable: dog
const
const
uses the same scope rules as let
, though it does not allow for redeclaration.
const x = 10
x = 11 // TypeError: Attempted to assign to readonly property.
It is possible to declare an array or object with const
and later assign or reassign values that they store:
const obj = { a: 1 }
obj.a = 2
console.log(obj) // { a: 2 }
const arr = [1]
arr.push(2)
console.log(arr) // [1, 2]
Using let
and const
and avoiding var
can help you code less bugs related to scope. If you use any linter like eslint, it's posible that it already points things like this to you.