Why do we need to use "constant variables"

I’m pretty new to coding but I need help understanding something. So at the beginning of the javascript course, there’s a whole section about let vs. var vs. const. What I don’t understand is why even use constant at all? It’s just the same thing as let but you cannot change it. Why not just use let always? And it’s not just javascript, a lot of other languages like swift has something similar to const. Can someone explain to me why const is used?

P.S here’s the link to the course → https://www.codecademy.com/courses/introduction-to-javascript/lessons/variables/exercises/const

Pretty much answers your own question. ‘const’ makes a declared variable immutable, regardless of type. It has no effect on the mutability of arrays and objects, though since it only makes the data container immutable, not the contents. This is especially useful when merging other scripts (plugins) with our own into the single namespace. It ensures that nothing can overwrite our variables.

On the whole, use ‘const’ for everything unless it needs to change, in which case use ‘let’. We can even use ‘const’ inside loops to redeclare a variable since the loop body is exited and reentered on each iteration.

1 Like