What’s the difference between var, let and const? Good thing you have this handy blog post to guide you!
The primary differences can be singled down to
- SCOPE
- REDECLARATION
- REASSIGNMENT
- and HOISTING
Scope:
Scope refers to the context in which the variable is able to be referenced.
- var: local (within a function)* or global **
- let: block scoped
- const: block scoped
*Imagine a function, with is an inner block (such an ‘if’ block). If a variable is reassigned within this inner block, and then called outside of the block (but still within the outer function) it will retain its reassigned variable.
**If a variable is declared with var in the global context, it actually becomes a property of the window object.
Reassignment:
The action of assigning a new value to a variable.
- var: can be reassigned
- let: can be reassigned
- const: cannot be reassigned***
***does not mean immutable! When the variable for an object is assigned, the properties and attributes of the object can be changed. But the reference in memory will only be able to point to one place.
Redeclaration:
The re-initialization of a new variable.
- var: can be redeclared
- let: cannot be redeclared
- const: cannot be redeclared
Hoisting:
Referencing a variable before it is declared.
- var: hoisted value= undefined
- let: hoisted value= uninitialized and will lead to error
- const: hoisted value= uninitialized and will lead to error