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.


The scope is the portion of code where the variable is visible. In JavaScript, every function has a scope.


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 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’

latir() // oof oof

console.log(dog) // ReferenceError: Can't find variable: dog


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]
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.