DEV Community

loading...

let vs const in JavaScript

uzairsamad profile image Muhammad Uzair ・2 min read

Let
A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block.
A variable declared with let can be updated within its scope. Unlikevar, a let variable cannot be re-declared within its scope.
let text= "say Hi";
text= "say Hello instead";

this will return an error.

let text= "say Hi";
let text= "say Hello instead";//error: Identifier 'text' has already been declared

However, if the same variable is defined in different scopes, there will be no error.

Hoisting of let
Just like var, let declarations are hoisted to the top. Unlike var which is initialised as undefined, the let keyword is not initialised. So if you try to use a let variable before declaration, you'll get a Reference Error.

You can redefine variables created with let but without using let key word

Const

Variables declared with the const maintain constant values. const declarations share some similarities with let declarations

const declarations are block scoped
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. So if we declare a variable with const, We can neither do this

const text= "say Hi";
text= "say Hello instead";//error : Assignment to constant variable.

                    **nor** 

const text= "say Hi";
const text= "say Hello instead";//error : Identifier 'text' has already been declared

Every const declaration, therefore, must be initialised at the time of declaration.

Hoisting of const

Just like let, const declarations are hoisted to the top but are not initialised.

-var declarations are globally scoped or function scoped while let and const are block scoped.

-They are all hoisted to the top of their scope. But while var variables are initialised with undefined, let and const variables are not initialised.

-While var and let can be declared without being initialised, const must be initialised during declaration.

-var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.

Discussion (0)

pic
Editor guide