Skip to content

Latest commit

 

History

History
97 lines (69 loc) · 3.53 KB

Ep-3-Hoisting in JS.md

File metadata and controls

97 lines (69 loc) · 3.53 KB

Episode 3: Hoisting in JavaScript (variables & functions)

Hoisting

Hoisting is a concept that enables us to extract values of variables and functions even before initialising/assigning value without getting errors. This happens due to the 1st (memory creation phase) of the Execution Context.

Let's observe the below code and its explanation:

Example 1:

getName(); // Namaste Javascript
console.log(x); // undefined
var x = 7;
function getName() {
 console.log("Namaste Javascript");
}

Output 1:

Namaste Javascript
undefined

Explanation:

  • In many other programming languages, accessing something that hasn't been created (defined) would result in an outright error.
  • However, in JavaScript, during the memory creation phase, it assigns 'undefined' to variables and allocates memory for functions.
  • During execution, JavaScript executes whatever is asked of it.
  • In JavaScript, execution happens line by line without prior compilation.
  • Because of this, if a variable is accessed before it's declared and initialized, it will print 'undefined' without throwing an error.
  • This behavior is not considered an error in JavaScript.
  • However, if a variable is removed or accessed before it's declared and not initialized, it will result in an error like Uncaught ReferenceError: x is not defined.

So in Episode 2, we learned that execution context gets created in two phases, so even before code execution, memory is created so in the case of a variable, it will be initialized as undefined while in the case of function the whole function code is placed in the memory.

image

Note: Not defined & undefined are not the same.

image

Let's see what's inside the getName

image

Example 2:

  getName(); // Namaste Javascript
  console.log(x); // undefined
  
  function getName() {
   console.log("Namaste Javascript");
  }

Output 2:

  Uncaught ReferenceError: x is not defined at <anonymous>:2:17

Let's remove the declaration of 'x' variable & see what happens

image

Hoisting through Arrow Function

  • In the Arrow function, it's considered a variable instead of a function.

Example 3:

  getName(); // Namaste Javascript
  console.log(x); // undefined
  
  var getName = ()  => {
   console.log("Namaste Javascript");
  }

Output 3:

  Uncaught TypeError: getName is not a function at <anonymous>:2:5

image

image

image

image

image

image

Watch Demo on YouTube