Everything you need to know about var, let and const.
Emmanuel Chikwendu Onah
Posted on January 5, 2022
Key points used in this article
Scope: Refers to a lexical environment at which variables and functions (be it expression or statement) are declared and made accessible as precedence.
Hoisting: A mechanism used by the JavaScript engine to take all variables and function declarations to the top of their respective scopes. If an engine supports JIT compilation, then it's in the JIT compilation phase that hoisting happens else during interpretation.
Things to know about var
- var is global and function scoped based only, e.g:
- var allows variable redeclaration(which doesn't make sense) and redefinition(which makes sense) within a singular scope, e.g:
- during hoisting, if a variable is accessed before its declarations as var variable, the compiler will hoist the var variable to the top of its scope with an implicit value of undefined, e.g:
- var variables declared inside block scope like if-statement, loops are not scoped meaning they can be accessed outside the block. e.g:
Things to know about let
- let is global, and block(anything with { }) scoped e.g:
- let doesn't allow redeclaration within a singular scope but allows redefinition, e.g:
- during hoisting, if a let variable is accessed before the declaration, the compiler throws a Reference error, unlike the var where an undefined value will be implicitly assigned, e.g:
Things to know about const
- const has the same features as the let above. The only difference is that its read-only and doesn't allow redefinition, but allows mutation for objects(e.g obj.propertyOrMethod =newValue ) if not frozen(Object.freeze(obj)) e.g:
In conclusion, var, let and const is not bad in my opinion it just depends on how you understand your program, but rarely do we use var this day.
💖 💪 🙅 🚩
Emmanuel Chikwendu Onah
Posted on January 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Angular 19 is Here, Next.js From China, NEWEST JavaScript Engine and more
November 24, 2024