- Hoisting means accessing the variables and functions before their declaration.
- The var declarations and named functions are hoisted in JavaScript. We can access the variables even before their declaration, but the variable value is undefined.
- whereas named functions also access even before their declaration. You can invoke the function; it will always work, but print the function, and it will print the actual function code
console.log(name) //undefined
display() /hello
var name ="shivaji";
function display(){
console.log("hello");
}
Example _2:
console.log(name) //undefined
display() //undefined
var name ="shivaji";
var display = function(){
console.log(" hello ");
}
Note: The anonymous function and arrow function are treated as variables, which is why it will print undefined.
- Arrows and functions are treated as variables.
- let and const declarations are hoisted, but they are hoisted very differently from var. These are in the temporal dean zone.
- Memory is assigned for var declarations, and these variables are attached to the global object, but in case of let & const declarations, they are allocated memory but in a different location rather than global; we can not access let & const declarations before we have put some value in them.
var a=10;
let b=2000;
console.log(window.a) //10
console.log(window.b) //undefined //it will stored in seperate memory location
Rules :
Let: redeclaration is not possible in the same scope. It throws a syntax error, won't execute any line of code in our program
console.log("error") // not execute
var a=10;
let a=2000;
Var: redeclaration is possible in the same scope.
console.log("no error")
var a=10;
var a=2000;