Why Programmers use const while declaring variable in JavaScript ?

prkskrs
Catalysts Reachout
Published in
3 min readNov 6, 2022

const

“const” has to be initialised.

const n1 = 20;
console.log(n1)

once you have assigned, you cannot reinitialise.

// Will throw error
const n2;
console.log(n2)

“const” can be scoped into blocks

const n1 = 20;if(n1<=20){
const n3 = 9;
console.log(`n3 : ${n3}`)
}
console.log(`n1 : ${n1}`)// Will throw error if you uncomment this line
// console.log(`n3 : ${n3}`)

“const” content can be modified

If I assign it as an object, JavaScript does not care if you change the object.
All it cares about is whether it is an object or not. Do not change it to a number or string. You can now update or change the inside of an object.

const movie = { "title" : "Avengers" }// will throw error
// const movie = 10;
// But changing inside object is fine
movie.title="test"
movie.year=100
movie.genre="Action"
console.log(movie)

you cannot do initialization in any of the ways

const n=1
n++ or n=n+1 or n=19

you cannot do loop with “const”

for(const i=0 ; i<10 ; i++)
{
console.log(i)
}
// will throw error at i++ at first time

let

“let” follow the same rule as “const” except it can be assigned and left uninitialized.

let n;
n=10;
n=[]
n={}
n="StringHere"
console.log(n)

you can always do loop with let

// will run perfectly
for(let i=0 ; i<10 ; i++)
{
console.log(i)
}

the value of undefined “let” variable is “undefined

let x;
console.log(x) // check console => x --> undefined

var

A classical way to initialise Javascript variables. The awful thing about var is It is expensive to manage in the browser.

Look at that! Right there, so the window will become this

Global object which already exist in the browser and any “VAR” variable will attach itself to this thing. You can imagine with a thousand variables later, you can attach yourself to this or stop, so it’s a security problem and it is taking an unnecessary memory.

Answer of the above question :

→ Always use “const” use “let” when you need to reassign variables
→ And avoid using “var
→ We need to clear things up, like that we should always use “const”.
If you need to reassign the value to the reserved variable, use “let” Otherwise, never use “var”, and in my programming experience with JavaScript till now, I’ve noticed that I barely use “let”, like only in loops. Otherwise, it’s constantly happening “const”.
Yes, if you require anything really, just use “const” all the time because of the optimisation.

Check GitHub for code : Click Here

--

--

prkskrs
Catalysts Reachout

backend developer and data scientist. currently studying computer science and constantly learning!