The quick answer:
var
has a different "scope" and it's normally better to useconst
andlet
const
is for variables that will not be updatedvar
is for variables that will be updated
Var
Before const
and let
the only way to declare a variable was with var
. The sope of var
-- where it can be accessed after it's been defined -- is global and function. So if it is defined outside a function it is globally scoped and available anywhere in the program. If it's defined in a function then it is function scoped and only available in that function. const
and let
on the other hand are block scoped. They are available in whatever block they are defined in. A block is anything inside curly brackets {}
The use of var
can be confusing in blocks such as for-loops where you can inadvertently update the global scope, when you only want to update the block scope. For example
for (let i = 0; i < 5; i++){
console.log(i) // 0/1/2/3/4
}
console.log(i) //undefined
for (var i = 0; i < 5; i++){
console.log(i) // 1/2/3/4
}
console.log(i) // 5
For this reason it is preferable to use const
and let
over var
const
When you assign a value to a variable using the const
keyword you tell JavaScript that you won't assign a new value to it. If you try, you will get an error.
It is worth remembering that while you can't update const
with a new value, you can still change the content of the variable. This is the case in objects and arrays. The below is valid
let
Use let
when you will need to update a variable later in your program. You still can't reassign a let
variable once it's been declared. For instance you couldn't use let cat = "mogy"
and then let cat = "felix"
but you can update the variable with cat = "felix"
.
Unlike with const, you an initialize a variable with let
without assigning it a value. The variable will then be undefined until you update it with a value
let number // number is undefined
number = 5 // number is 5