DEV Community

Cover image for What's the difference between var, const and let
John Palmgren
John Palmgren

Posted on

What's the difference between var, const and let

The quick answer:

  • var has a different "scope" and it's normally better to use const and let
  • const is for variables that will not be updated
  • var 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
Enter fullscreen mode Exit fullscreen mode
for (var i = 0; i < 5; i++){
  console.log(i) // 1/2/3/4
}
console.log(i) // 5
Enter fullscreen mode Exit fullscreen mode

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.

Untitled (Postcard) (1).png

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

Untitled design (9).png

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
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
thenickest profile image
TheNickest

Doesn’t the const key word make a variable a constant? Like: if we assign a value with const, we assign it to a constant and not to an immutable variable. I was always wondering.

Collapse
 
johnpalmgren profile image
John Palmgren

That's right. When you use the const keyword javasctipt will expect that that value won't change. And in fact, will throw an error if you try to update it.