What is Hoisting in javascript ?

introduction

During an interview this question is asked to me that what is hoisting so I thought why not deep dive into it and find what is it .

Hoisting:

so whenever javascript code is run using the javascript engine , it create global execution context, it is divided into two parts one is creation, execution

During creation it will move all the variable declaration and function declaration to the top.

Lets see an example

what will happen if I run the below code ?

console.log(counter)

this will give us the reference error since there is no counter declared or initialized,.

Uncaught ReferenceError: counter is not defined
    <anonymous> http://127.0.0.1:5500/index.js:1

What will happened if I run this time ?

var counter = 0
console.log(counter)

it will print zero

What will happen If i move counter initialization after the console.log ?

console.log(counter)
var counter = 0

here the output is undefined so this time it is undefined rather than reference error it means here , here what happened during the global execution context creation phase , the javascript engine moved the declaration to the top

it means the code looks like this to the browser.

var counter
console.log(counter)
counter = 0