Understanding JavaScript Hoisting
In JavaScript, all variable declarations are "hoisted" to the top of their containing scope. This means the declaration part of variables (var name;) are moved to the top of the function or global scope. However, the initialization (name = "John") remains where you've written it in the code. This is why you are encountering the issue in your code.
Here's a breakdown of your code with a hoisting perspective:
From the code snippet, it's evident that you logged greeting before initializing it. At the point of console.log(greeting), the variable greeting exists due to hoisting but it holds the default value of undefined because its initialization ("Hello " + name) occurs later in the code.
How to Fix the Issue
To remedy this, ensure that you always initialize your variables before you try to use them:
By reordering the statements, the program will work as expected, printing “Hello John”. This is because by the time console.log(greeting) is executed, the greeting variable has already been initialized with the desired string.
Conclusion
Understanding how hoisting works in JavaScript is crucial, especially when working with var declarations. It prevents issues related to the execution order of your code and makes debugging far easier. Consider also modern practices using let or const for variable declarations to restrict the scope more effectively and avoid hoisting issues.