Skip to content

38 Hoisting

Biswajit Sundara edited this page Aug 18, 2023 · 1 revision
  • Hoisting means we can use the variables, methods before declaring them.
  • It means no matter where the functions or variables are declared
  • They are moved to the top of their scope regardless of their scope is local or global.
  • However, it's important to note that only the declarations are hoisted, not the initializations or assignments.

1. No Hoisting

This is how we usually code, declare the variables/functions first and then invoke them.

var x=7;
function getName(){
    console.log("Biswajit");
}

getName();
console.log(x); //Output - Biswajit, 7

2. Variable Hoisting

  • Even though x is accessed before it is declared and assigned a value, it does not throw an error.
  • This is because during hoisting, the declaration var x is moved to the top of the scope
  • But the assignment (x = 5) remains in place.
  • So, before the assignment, the variable has a value of undefined.
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5
  • Memory allocation happens first, and during memory allocation x value was set to undefined

3. Function Hoisting

  • The function greet() is called before it is defined. Due to hoisting, the function declaration is moved to the top,
  • allowing it to be called successfully.
greet(); // Output: "Hello, World!"
function greet() {
  console.log("Hello, World!");
}
  • During memory allocation the method was allocated the memory, so we are able to invoke it during execution.

4. Scenarios

  • What happens if we try to print the function name before the declaration.
  • During memory allocation the getName will be initialized with the code of the function
console.log(getName); // output - [Function: getName]

function getName(){
    console.log("Biswajit");
}
  • What happens if we change the function to arrow function
  • This will throw an error can't invoke getName as its not defined
  • Arrow functions are treated as variables
  • During memory allocation getName will have the value undefined
  • if we change to var from const, it will print undefined
// getName();  //will throw error
console.log(getName); // will throw error

const getName = () =>{
    console.log("Biswajit");
}

5. Scenarios

  • What will happen if we try to access X without declaring it.
  • This will throw an error saying X is not defined.
  • The reason is during memory allocation no space is reserved for variable X
  • So when it tries to access the value during execution it complains that X is not defined.
console.log(x);

Clone this wiki locally