Hoisting and Closures in JavaScript
Hoisting and closures are the two features that JavaScript have and confuse the beginners. They are the features a professional JavaScript programmer must know.
Hoisting and closures are both related to functions, and especially refer to scopes in functions.
Scopes in JavaScript are defined by functions, not by braces as in C language.
- Hoisting
Hoisting refers to the case that named functions are in scope within the entire function within which they are declared.
- Closure Closure refers to the case that variables being defined within its functional scope can only be accessed from its scope but not outside of its scope.
Closures can be best used for protecting some variables by making them being private.
From the above example we can see that closure is closely related to IIF(Immediatelly Invoked Function).When IIF is used, a closure is being created automatically. Actually that’s the main application scenario for IIFs.