Javascript var, let and const

People always got confused about how to use var, let and const when declare a variable, especially for Javascript beginners. Today we are going to talk about their differences from various perspectives:

Scope

Var can be used for declaring globally scoped variable and function scoped variable.

let and const are block scoped, var is not block scoped.

Block scope: “The block is delimited by a pair of braces (“curly brackets”)”. Such as if…else…statement and loops.

You can see that we can still access c but not d and E.

let and const can still be used to declare global variables, they just do not create properties of the window object when declared globally (in the top-most scope).

Declare and Update

var variables can be update and re-declared within its scope:

let variables can be updated but cannot be re-declared

const variables can neither be updated nor re-declared

The const keyword makes a variable itself immutable, not its assigned content. If you use const to declare an object, the object itself can still be altered.

Hoisting

“Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

All of them are hoisted to the top of their scope. var variables are initialized with undefined, let and const variables are not initialized. So when you try to access variable before declaration, var variable will return undefined, but let and const variables will return reference error:

Initialization

var and let can declare variables without assigning initial values to them, const must be initialized during declaration.

Resources: