Javascript has lexical scope - the variable values are available and valid based on their position. The same is applicable to functions.
At the same time declarations are brought to the top of their block at compile time. In other words, they are hoisted at the time of compilation, and hence variables and functions are available to statements accessing them before the actual declaration.
Consider the following function -
|
|
Even though the function is declared after the actual call, the above piece of code works without issues.
However, this might be an issue if you need functions to not have global scope, i.e., function should exist only at certain times in the code.
This can be achieved using one of the following options -
Use named functions
The below code will throw an error since getSum
is not available at the time of being called.
|
|
Use the more modern notation
Use arrow functions for better readability.
|
|
Or, go extreme and have a function without its properties :)
Use IIFE
Use ‘immediately invoked function expression’ if you don’t really find it necessary to have reusable function.
|
|