When declaring a variable in Javascript, you have three options: let, var, const. Here we’ll talk about all three ways and how they handle in certain scenarios.

Scope

Previous to ES2015, Javascript only had two scopes; global and function. With ES2015 and its introduction of two new keywords, let and const, a new scope was introduced; the block scope.

Global Scope: any variables declared outside of functions are accessible from anywhere in the program.

Function Scope: variables declared within a function are only accessible with that function. If they are declared using var, they will be available anywhere within the function, even if declared within inner blocks.

Block Scope: let and const have block scope. var does not.

However, if we use let or const, any declared variables are limited to the blocks that they were declared in:

Declaration

When we declare a variable using var, it is figuratively hoisted to the top of the code before execution. This allows you to use it before it’s declared, though it’ll be initialized with a value of undefined until it gets to the line where it’s assigned a different value¹:

let and const are also hoisted but are not initialized with a value until the compiler reaches the declaration:

if let is declared but not assigned a value or is used before being assigned a value, it’s value will be undefined. This is known as a Temporal Dead Zone — the time between initialization and assignment when using let.

const must be assigned a value when declaring it.

const must be assigned a value at declaration.

Putting it all together:

Mutability

All three of these options are mutable. With var and let, this is well-known and expected. But const? Behold:

//  output: {name: 'Wishbone', color: 'red'}

const only prevents reassignment or redeclaration, it doesn’t grant immutability. Remember this when declaring objects and arrays using it.

Conclusion

These are the main differences between var, const, and let. It is generally best to use const when you do not plan on reassigning a variable, and let when you are. var still has its uses, but I won’t go over them here. Most headaches can be avoided if you just remember to declare your variables at the top of any function or block in which you plan to use them. Good luck!

¹all three will be assigned a value of undefined during the initialization phase. However, when using var, declaration and initialization are coupled and therefore its time in this state is more prominent.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store