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:57] – 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 24: | Line 26: | ||
Hoisting does not apply to variables declared with **let** and **const**; trying to access them before their declaration will result in a **ReferenceError**. | 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 ===== |
java-script/hoisting.1691528258.txt.gz · Last modified: 2023/08/08 23:57 by odefta