java-script:hoisting
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
java-script:hoisting [2023/08/08 23:55] – odefta | java-script:hoisting [2023/08/09 00:32] (current) – odefta | ||
---|---|---|---|
Line 4: | Line 4: | ||
===== Variable hoisting ===== | ===== Variable hoisting ===== | ||
+ | |||
+ | ==== Using var keyword ==== | ||
;;;The variable declaration using var is hoisted, but the initialization is not.;; So, if you reference a variable before it's initialized, | ;;;The variable declaration using var is hoisted, but the initialization is not.;; So, if you reference a variable before it's initialized, | ||
Line 20: | Line 22: | ||
console.log(a); | console.log(a); | ||
</ | </ | ||
+ | |||
+ | <note important> | ||
+ | Hoisting does not apply to variables declared with **let** and **const**; trying to access them before their declaration will result in a **ReferenceError**. | ||
+ | </ | ||
+ | |||
+ | ==== Without any keyword ==== | ||
+ | |||
+ | ;;; | ||
+ | |||
+ | Example: | ||
+ | <code javascript> | ||
+ | console.log(myVar); | ||
+ | myVar = " | ||
+ | console.log(myVar); | ||
+ | </ | ||
+ | |||
+ | In this case, **myVar** is not declared or initialized before the first console.log, | ||
+ | |||
+ | If you were to declare the variable without initializing it within a function, **it would be hoisted as a property of the global object** (such as window in a browser environment): | ||
+ | < | ||
+ | function myFunction() { | ||
+ | myVar = " | ||
+ | } | ||
+ | myFunction(); | ||
+ | console.log(window.myVar); | ||
+ | </ | ||
+ | This behavior can lead to unexpected results and make the code harder to understand and maintain. | ||
===== Functions ===== | ===== Functions ===== | ||
Line 37: | Line 66: | ||
<note important> | <note important> | ||
- | Hoisting does not apply to variables declared with **let** and **const**; trying to access them before their declaration will result in a **ReferenceError**. | + | ;;;Function expressions (including arrow functions) are NOT hoisted like function declarations;;;, so their behavior is more like that of variables declared with **var**. \\ |
- | </ | + | |
- | + | ||
- | <note important> | + | |
- | ;;;Function expressions (including arrow functions);;; are not hoisted like function declarations, | + | |
Only the variable declaration is hoisted, not the initialization with the function value. \\ | Only the variable declaration is hoisted, not the initialization with the function value. \\ | ||
Example: | Example: |
java-script/hoisting.1691528128.txt.gz · Last modified: 2023/08/08 23:55 by odefta