concepts and implementations
The above snippet is Hoisting in action.
- When reading code it may appear that a variable or function is being used before being defined
- Declaring any variable or function in code is equal to declaring it at the top
Variables declared OUTSIDE of functions are called GLOBAL. Variables declared INSIDE functions become LOCAL to that function. Local variables have local scope, they can ONLY be accessed within the function in which they were defined.
Declaration vs. Definition vs. Simultaneous D&D
- Declaration — HOISTED
- Definition — NOT HOISTED
- Simultaneous D&D — Declaration is HOISTED, Definition NOT HOISTED
The exact same concept applies to functions.
Line 2 spits out the expected ‘something’ response because the function declaration was hoisted to the top of the code.
Line 8 spits out an err b/c even though the variable declaration WAS hoisted, the definition was NOT.
- Always define variables before you use them.
- Variables should be declared at the top of the function scope to make your code readable and to make scope(and intent) clear to other developers.
- It is usually best to define functions lower in the code to keep them out of the way.