What is the difference between let, const, and var when declaring variables in JavaScript?
14617-Jun-2024
Updated on 17-Jun-2024
Home / DeveloperSection / Interviews / What is the difference between let, const, and var when declaring variables in JavaScript?
Ravi Vishwakarma
17-Jun-2024let
,const
, andvar
keywords are used for variable declarations, but they have some key differences in terms of scope, hoisting, and mutabilityvar:
var
are function-scoped when declared inside a function, or globally scoped when declared outside any function.var
are hoisted to the top of their scope and initialized withundefined
. This means you can use avar
variable before it's declared in the code.var
can be redeclared and reassigned.let:
let
have block scope, which means they are only accessible within the nearest enclosing curly braces{ }
.let
are hoisted to the top of their block but are not initialized. This means you cannot access alet
variable before it's declared in the code.let
can be reassigned, but you cannot redeclare them in the same scope.const:
let
, variables declared withconst
have block scope.const
are also hoisted to the top of their block but are not initialized. You cannot access aconst
variable before it's declared.const
must be initialized with a value and cannot be reassigned to a different reference. However, their value may be mutable (e.g., properties of an object or elements of an array can be changed).