Aug 29, 2017 · 1 min read
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:
sayHellogets hoisted along with the function body, as it is a function declaration. - line 4: The variable
hellogets hoisted with a valueundefined, as it is a function expression. - line 8:
hellogets hoisted, over-riding the value ofhello(which wasundefined) with the body of the function{ console.log('Hey!') }
During the execution phase:
- line 1: Invoke
sayHello - line 4: The value of
hellogets overridden again, as we re-assignfunction () { console.log('Hello!') }tohello. - line 12: Invoke
hello
This is why it prints out Hello!.
I hope this helps :)
