Hoisting, Functions, and Closure
Learn about hoisting, functions that return functions, and closures.
We'll cover the following...
Hoisting
Functions that are defined using a function declaration are automatically hoisted to the top of a program’s scope. This means that they can be called before they’ve been defined. For example, in the following code, the function
hoist()
can be called before it’s actually defined:
// function is called at the start of the codehoist();// ...// ... lots more code here// ...// function definition is at the end of the codefunction hoist() {console.log('Hoist Me!');}
This can be quite useful, because it means that all function definitions can be placed together, possibly at the end of a program, rather than every function having to be defined before it’s used.
An error will be thrown if we attempt to refer to a variable before it has been declared using const
and let
. For this reason, we should try to declare any variables at the beginning of a block so that hoisting isn’t necessary.
This means that a function expression (where an anonymous function is assigned to a variable) can’t be called before it has been declared, unlike a function declaration.
This is probably the biggest difference between function declarations and function expressions, and it may influence our decision regarding which one to use. Some people like the fact that using function expressions means we’re required to define all functions and assign them to variables prior to using them, while others prefer to have the option to keep all their functions in one place as function declarations.
Functions that return functions
We’ve already seen that functions can accept ...