In the above code, I called Printname function before function declaration, but I get output in the console because of hoisting. what hosting does is when we compile the code, the compiler hoisted all declaration to the top of their scope. Hoisting does not mean all declaration are physically move to the top of their scope. What happen is before executing your code, the compiler goes through top to bottom in your code and creates a space in memory for all declaration in code. After complete the compilation, your code start execute.
- Global scope
- Local scope
In above code variable called age in a global scope because it declared at the root of the script. That age variable can use both inside and outside a function in this script.
In above code variable called age in local scope because it declared in the inside of a function. We cannot access a local variable from the outside of a function. If we try to access that local variable from the outside of a function, we will get an error as an output like in above.