re: Var, let and const- what's the difference? VIEW POST

FULL DISCUSSION
 

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

 

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

 
 
 

'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."

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.

This was incredibly helpful, and a great TLDR!

code of conduct - report abuse