Skip to main content

Command Palette

Search for a command to run...

JavaScript Hoisting

Published
1 min readView as Markdown
JavaScript Hoisting

In JS any variables and functions trying to access before the declaration is known as Hoisting.

Let's see the First example:

  1     var num = 80
  2
  3     function declaration (){
  4        console.log("creative world");
  5     }
  6
  7     declaration()
  8     console.log(num);

   //Web & Terminal here 
    creative world
     80

This is normal, we declare the variable & function then it will access then it gives what is actual output creative world & 80.

Let's see the Second example:


  1     declaration()
  2      console.log(num);
  3
  4     var num = 80
  5     function declaration (){
  6        console.log("creative world");
  7     }
  8

   //Web & Terminal here 
    creative world
    Undefined

In the second example, we can see the variables and functions we are trying to access before the declaration so, the output for the function is the creative world, for the function it is given the correct answer because, in Execution Context, it is a clear explanation like "the whole function code is literally copied over memory space".

the next output is given 'Undefined' instead of 80 because a JS code is treated in memory like an objective/key-value pair.