Declarations vs. Initializations
let myName; (myName has no value but has been declared)
Initialization just means that you’ve assigned an initial value to a variable.
let myName = ‘Bryan’; (declared and initialized)
Closures are functions inside another function that have access to the outer function’s variables. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables. The inner function also has access to the outer functions parameters.
Closures are useful because they let you associate some data with a function that operates on that data.
Performance Considerations with Closures
One thing to remember with closures is that it’s not always smart to unnecessarily create functions within other functions if they’re not needed. Doing so will negatively affect script performance both in terms of processing speed and memory consumption.
Hoisting is when variables and function declarations are moved to the top of their scope before code execution. This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local and variable declarations are processed before any code is executed.undeclared variables do not exist until code assigning them is executed.
Assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed. This means that, all undeclared variables are global variables.
In ES6, a let variable’s scope is bound to the block in which it is declared and not the function in which it is declared.
- Variable assignment takes precedence over function declaration
- Function declarations take precedence over variable declarations
Function declarations are hoisted over variable declarations but not over variable assignments.
In ES5, while using var, trying to use undeclared variables will lead to the variable being assigned a value of undefined upon hoisting.
In ES6, when using let and const, using undeclared variables will lead to a Reference Error because the variable remains uninitialised at execution.
Also published on Medium.