Hoisting and Scope
Last updated
Last updated
Here is a good article filled with awesome Hoisting and variable declaration goodness. Below is an overview.
What happens if we call a function before it is defined?
Interpreted languages like Javascript work with functions differently than compiled languages like C++. The interpreter looks through the entire code file and decides the 'proper' order of certain code blocks. For example, it prioritizes function declarations over runnable code.
Variables and functions are declared within other blocks of code (a loop, for example).
Can I use a variable anywhere I want?
Imagine if we never released the memory used by a variable. When a variable is created, memory is allocated for that data. When the block of code where that variable exists has ended, the memory is released (no longer needed). This helps with the efficiency of the program.
The other thing to note is the use of the term let
in the example above. In Javascript, there are three ways to create variables (which is quite dangerous). Many people will have their own opinions but it is safest to always declare your variables with let
instead of var
and certainly never leave out the declaration.
Why do I need to declare my variables, anyway? Javascript lets me write a = 4
and it still works.
<< More to come >>