var, let, const — what’s the difference?

ES6 introduced two new ways to declare a variable: let and const. var can still be used, but let and const make code easier to read and understand as they signal how a variable is used. Let’s see what the differences are.

var

“The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.” — MDN Description

Using var signals that the variable is function-scoped (or global if declared outside a function).

let

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.” — MDN Description

Using let signals that:

  • the variable may be reassigned. Useful as a counter in a loop for example.
  • the variable can’t be used before its declaration.
  • the variable can only be used in the block it is declared in. A variable declared with let is block-scoped and not function-scoped.

let scope vs var scope:

When using var you can reassign your variable. So, you could be creating two variables with the same name twice without knowing it. let doesn’t permit that if you are in the same block:

const

“This declaration creates a constant whose scope can be either global or local to the function in which it is declared. An initializer for a constant is required; that is, you must specify its value in the same statement in which it’s declared (which makes sense, given that it can’t be changed later). The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object’s contents (e.g. its parameters) can be altered.” — MDN Description

Using const signals that:

  • the variable identifier may not be reassigned.
  • the variable can’t be used before its declaration.
  • the variable is block-scoped.

let vs const reassignment:

const properties reassignment:

This is just a quick overview of the main differences between the three variable declarations options. If you want to learn more about it, below are some interesting links as well as the official documentation.


Like what you read? Give Lili Ouaknin Felsen a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.