Understanding var, let and const with Examples

Var

Using var declares either a locally(within function) scoped variable or a globally scoped variable.

When var is used outside a function, it declares a globally scoped variable.

This is similar to adding a property to window object directly, while there is a difference: you can’t delete the variable declared using var.

When var is used inside a function definition, it creates a local variable which is only available within the function:

If you happen to forget to add var in a function when declare a variable, it becomes a globally scoped variable.

It may not be what you intended to do, for example:

The variables declared with var are hoisted, which means you can use the variables even before it reaches the line in the code it declares the variable.

Note that if you try out above example in Chrome console, copy and paste above code snippet in one shot, i.e. don’t copy and execute each line one at a time; otherwise you’ll get a “Uncaught ReferenceError: a is not defined” error.

Let

Using let declares a block scoped variable.

The variable declared with let is only available within the code block it is defined.

Unlike var, the variables declared with let is not added to window object as a property even if it is globally accessible.

Unlike var, you can not re-declare a let variable in the same scope.

A fun fact is that both Chrome (84.0.4147.105) console and Microsoft Edge (83.0.478.61) allow this redeclaration, while FireFox (78.0.2) and Safari (13.1.1) don’t.

The variables declared with let are not hoisted to the top, hence let variable is still not yet initialized with undefined if user use it before declaration. That’s why there is a temporal death zone, i.e., browsers will report an error if one use the let variable before declaration.

Const

Using const declares and initializes a block scoped constant. If the constant is a primitive type (string, number, bigint, boolean, undefined, and symbol) or null, the value could not be altered after initialization.

While if it points to an object, the properties can be modified/added/deleted. The only thing that cannot be modified is the memory address of the object to which the constant is pointing.

Like let, const constants are block scoped.

In addition, browsers don’t allow redeclaration of constant in the same block scope, even in Chrome and Microsoft Edge.

Like let, const constants are not available before declaration, i.e. browser will report an error if one use it before declaration.

--

--

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
Wenhe Qi

A lifelong learner who has enthusiasm for sharing knowledge; a developer who loves bringing ideas to life.