In JavaScript, we can access the variables and functions even before they are initialized or assigned a value.
Look at the code below:
greet(); //JavaScript
console.log(x);//Undefined
function greet(){
console.log("JavaScript")
};
var x = 28;
In many other programming languages, this would result in an error. However, in JavaScript, this code runs without any error. JavaScript executes code line by line, but before execution, memory is allocated for all variables and functions. During the two phases—Memory Creation and Code Execution—the Memory Creation Phase assigns undefined to variables(x) and stores the entire function code(greet()) in memory. Here, we are trying to access greet even before it is initialized (We can access the function anywhere before it is initialized). If we remove (x = 28), it will result in an Uncaught ReferenceError: x is not defined.
console.log(greet); //ƒ greet(){console.log("JavaScript");}
console.log(x);//Uncaught ReferenceError: x is not defined
function greet(){
console.log("JavaScript");
};
Hoisting is the concept of moving declarations to the top of their scope during the compile phase, before the code is executed. Declaring a variable or function means creating or defining its name so that the JavaScript engine recognizes its existence. Initialization refers to assigning a value to a declared variable or defining the code inside a function. In JavaScript, var is hoisted. However, only the declaration is hoisted, not the initialization.
greet(); //Declaring a function
var x; // Declaring a variable
console.log(x);//Undefined
function greet(){
console.log("JavaScript")
};
x = 28;// Initializing a variable
greet()
var greet = () => {
console.log("JavaScript");
}; //Uncaught TypeError: greet is not a function
When we run this code, we will get an error. This will happen because, during the memory creation phase, greet will be assigned undefined, as it will be treated as a variable.
Credits to Akshay Saini.
Top comments (3)
You should add tags to your post @ramya_srim so that it makes your article better and it will reach more people select at most 4 tags for example #javascript
Thank you! I'll make sure to add the tags as suggested.
Am just a moderator okay, you have a nice and impactful article there by the way