DEV Community

Discussion on: Var, let and const- what's the difference?

Collapse
 
ashbrandn profile image
Ashley Brandon

Why should var be avoided?

Collapse
 
mushin108 profile image
Mushin108

"Variable shadowing"

Collapse
 
sgmallon profile image
Scott Mallon • Edited

'Var' allows for re-declarations in code which does not throw errors and can create unintended side-effects in your code.

'Let' allows for variable reassignment but not for duplicate declarations (block-scoped), much like strongly typed languages like C# and Java.

'Const' allows for declaration once and for assignment once, and can never be re-declared or reassigned (block-scoped). For instance, I use 'const' for inline function declarations, so that I don't accidentally redefine this function's behavior at some later point in time by mistake. Even though I am unlikely to do so, it is just safer for myself and others to work on.

To paraphrase Sarah more generically:

"While it is not a problem if you knowingly want a var to be a certain value at a certain point in code, it becomes a problem when you do not realize that this same var has already been declared/defined before or, even worse, has had other functions operate on this var without your knowledge."

So, in other words, it's a much better idea to use 'let' and 'const' in order have safer control over your variables and constants.

Thread Thread
 
oizabaiye profile image
Oiza

This was incredibly helpful, and a great TLDR!