Var, Let and Const in JavaScript
2 min readJul 30, 2022
In JavaScript, var
, let
, and const
are used to declare variables, but they have some differences in terms of scope and mutability:
var
: Before the introduction oflet
andconst
in ECMAScript 2015 (ES6),var
was the primary way to declare variables in JavaScript. Variables declared withvar
have function scope or global scope, which means they are accessible throughout the entire function or globally if declared outside any function. Hoisting is also applicable tovar
variables, allowing them to be accessed before they are declared. Additionally,var
variables can be redeclared and reassigned.let
: Introduced in ES6,let
allows the declaration of block-scoped variables. Variables declared withlet
are limited in scope to the block, statement, or expression in which they are defined. This means they are not accessible outside of that block. Unlikevar
,let
variables are not hoisted, so you need to declare them before using them in the block.let
variables can be reassigned, but they cannot be redeclared within the same scope.const
: Also introduced in ES6,const
is used to declare variables with block scope that are meant to be constants. Once a value is assigned to aconst
variable, it cannot be reassigned or redeclared within the same scope.const
variables are also not hoisted and must be assigned a value at the time of declaration. It's important to note that whileconst
prevents reassignment of the variable itself, it does not make the assigned value immutable. If the assigned value is an object or an array, its properties or elements can still be modified.
In summary, var
has function scope, let
has block scope and allows reassignment, while const
has block scope and is used for declaring constants that cannot be reassigned. The choice between let
and const
depends on whether you need to change the value of the variable or not.