Now let’s talk about Hoisting.
A variable declaration lets the system know that the variable exists while definition assigns it a value.
Variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it’s declared. This behavior is called “hoisting”, as it appears that the variable declaration is moved to the top of the function or global code.
Just remember, variable declarations and function definitions are hoisted to the top. Variable definitions are not, even if you declare and define a variable on the same line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
To make things easier to read
- Declare all of your variables at the top of your function scope so it is clear which scope the variables are coming from.
- Define your variables before you need to use them.
- Define your functions at the bottom of your scope to keep them out of your way.