Chidiebere Ohalewe
3 min readDec 4, 2022

Difference Between Var, Let and Const.

First of var, let and Const are ways you can use to declare a variable in JavaScript.

What is a variable you ask?.

Variables are essentially pointers or references to some data in a machines memory and the pointer can dynamically be changed to reflect the true state of the data we’ve “labelled.”

Now we’re about to dive into differences between the aforementioned variables.

First is Var.

Var is a reserved keyword which is followed by a reference variable name.

The name defined after the keyword can then be used as a pointer to the data in memory.

Using var is the oldest method of variable declaration in JavaScript.

Var name = “ chidi";

Scope of var.

When defined defined within a function -any Var is restricted to that function, when defined outside of a function, a var is global.

The issue with Var is that it’s not block-scoped.

When you declare a variable within a code block using curly braces {} its scope “flows out" of the block.

Declaring variables using the var declarations everywhere in your code can lead to confusion, overwriting of existing global variables and by extension bugs.

This is where let and Const kicks in.

Let
The let declaration was introduced with Es56 and has since become the preferred method for variable declaration.

It is regarded as an improvement over Var declaration and is block- scoped ( variables that can be accessed only in the immediate block)

This time around - the firstName referring to "Jane" and the firstName referring to "John" don’t overlap! The code results in:

The firstName declared within the block is limited to the block in scope and the one declared outside the block is Available globally. Both instances of firstName are treated as different variable references, since they have different scopes.

Const.

The const declaration was introduced with Es6 alongside let, and it is very similar to let , Const points to data in memory that holds constant values, as the name implies, Const reference variables cannot be reassigned to a different object in memory.

Which then results in;

Uncaught Syntaxerror: identifier 'name' has already been declared.

The scope of a variable defined with Const keyword , like the scope of let declaration is limited to the block defined by curly braces ( a function or a block)

The main distinction is that they cannot be updated or re-declared , implying that the value remains constant within the scope

So basically what the above is trying to explain to the reader is that ;

  • Const is preferred to let which is preferred to var. Avoid using var.
  • Let is preferred to const when it’s known that the value it points to will change over time.
  • Const is great for global, Constant values.
  • Libraries are typically imported as Const.