User Tools

Site Tools


java-script:hoisting

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:hoisting [2023/08/08 23:55] odeftajava-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, it will return undefined. \\  ;;;The variable declaration using var is hoisted, but the initialization is not.;; So, if you reference a variable before it's initialized, it will return undefined. \\ 
Line 20: Line 22:
 console.log(a); // 5 console.log(a); // 5
 </code> </code>
 +
 +<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>
 +
 +==== Without any keyword ====
 +
 +;;;Variables that are declared without any keyword;;; (such as var, let, or const) ;;;are not hoisted;;;. Rather, **they become global variables** (if not already within a global scope), and their declaration and initialization happen at the line where they are assigned. \\ 
 +
 +Example:
 +<code javascript>
 +console.log(myVar); // ReferenceError: myVar is not defined
 +myVar = "abc";
 +console.log(myVar); // "abc"
 +</code>
 +
 +In this case, **myVar** is not declared or initialized before the first console.log, so attempting to access it results in a **ReferenceError**.\\ \\ 
 +
 +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):
 +<code>
 +function myFunction() {
 +  myVar = "abc";
 +}
 +myFunction();
 +console.log(window.myVar); // "abc" in a browser environment
 +</code>
 +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> 
  
 <note important> <note important>
java-script/hoisting.1691528157.txt.gz · Last modified: 2023/08/08 23:55 by odefta