{
// belongs to upper/global scope
var a = 'variable'
}
for (var i = 0; i < 5; i++) {
console.log(i)
}
Block scope with let & const
let & const came with ES6
Disables hoisting
Good for garbage collection
{
console.log(a); // ReferenceError
console.log(b); // ReferenceError
let a = 5;
const b = {prop: 'value'};
}
Hoisting
Moving variable and function declarations to the top of the scope
// 1 and 2 have same effect
/* 1 */
var a;
console.log(a);
a= 2;
/* 2 */
console.log(b);
var b = 3;
Closures
Open access to scope for later use
Closures are already exist, you should learn to see
Provides keeping variables private
function addNumber(num) {
return function(anotherNum) {
return num + anotherNum;
}
}
var addTwo = addNumber(2);
addTwo(3) // remembers num as 2 and returns 3