In the 5th example, I tried to call hello method after the ‘hello’ function definition.
Balajee Ks
1

Hey Balajee,

Thanks for your question! Indeed the below will print out Hello!. And actually it is for the exact same reason why the example 5 would print out Hello! due to hoisting.

I always find that the best way to understand what’s happening is to follow the events in order, line by line.

During the memory creation phase:

  • line 3: sayHello gets hoisted along with the function body, as it is a function declaration.
  • line 4: The variable hello gets hoisted with a value undefined, as it is a function expression.
  • line 8: hello gets hoisted, over-riding the value of hello (which was undefined) with the body of the function { console.log('Hey!') }

During the execution phase:

  • line 1: Invoke sayHello
  • line 4: The value of hello gets overridden again, as we re-assign function () { console.log('Hello!') } to hello.
  • line 12: Invoke hello

This is why it prints out Hello!.

I hope this helps :)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.