An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
January 5, 2022 04:31 am GMT
Original Link: https://dev.to/emmanuelonah/everything-you-need-to-know-about-var-let-and-const-56a5
Everything you need to know about var, let and const.
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.
Original Link: https://dev.to/emmanuelonah/everything-you-need-to-know-about-var-let-and-const-56a5
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To