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 35: | Line 64: | ||
In this case, the entire function declaration is hoisted, so you can call it even before the point in the code where you define it. | In this case, the entire function declaration is hoisted, so you can call it even before the point in the code where you define it. | ||
- | |||
- | <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**. | ||
- | </ | ||
<note important> | <note important> |
java-script/hoisting.1691528157.txt.gz · Last modified: 2023/08/08 23:55 by odefta