Javascript let,var,const
One of the features that came with ES6 is the addition of let
and const
, which can be used for variable declaration, not just var as it was originally. In this article, we’ll discuss var
, let
and const
with respect to their scope, use, and hoisting.
Scope essentially means where these variables are available for use. var
declarations are globally scoped or function/locally scoped.The scope is global when a var
variable is declared outside a function. This means that any variable that is declared with var
outside a function block is available for use in the whole window.var
is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function. var variables can be re-declared and updated, this means that we can do this within the same scope and won’t get an error. Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. var
variables are hoisted to the top of their scope and initialized with a value of undefined
.
let
is now preferred for variable declaration. let is block scoped. A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block.So a variable declared in a block with let
is only available for use within that block. let can be updated but not re-declared. Just like var
, a variable declared with let
can be updated within its scope. Unlike var
, a let
variable cannot be re-declared within its scope. Just like var
, let
declarations are hoisted to the top. Unlike var
which is initialized as undefined
, the let
keyword is not initialized. So if you try to use a let
variable before declaration, you'll get a Reference Error
.
Variables declared with the const
maintain constant values. Like let
declarations, const
declarations can only be accessed within the block they were declared. const cannot be updated or re-declared, this means that the value of a variable declared with const
remains the same within its scope. It cannot be updated or re-declared. Every const
declaration, therefore, must be initialized at the time of declaration. This behavior is somehow different when it comes to objects declared with const
. While a const
object cannot be updated, the properties of this objects can be updated. Just like let
, const
declarations are hoisted to the top but are not initialized.