DEV Community

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

Collapse
 
jeansberg profile image
Jens Genberg

Good post. I wasn't sure about these. Just knew that 'var' should be avoided.

I think you have typo here. Remove the second 'let' from the first code block. :)
So while this will work,
let greeting = "say Hi";
let greeting = "say Hello instead";
this will return an error.
let greeting = "say Hi";
let greeting = "say Hello instead";//error: Identifier 'greeting' has already been declared

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks a lot for pointing that out. I'll correct it right away.

Collapse
 
itayko profile image
itayko

Thank for a great article

Error still exists in the article..

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!