Definition: A closure is a function that remembers the variables from its outer (enclosing) function scope even after the outer function has finished executing.
Example:
function outer() {
const a = 4;
function parent() {
const b = 6;
function add() {
console.log(a + b);
}
return add;
}
return parent();
}
const add1 = outer();
add1(); // Output: 10
Output:
10
outer()
function defines variable a
and returns parent()
.parent()
defines variable b
and returns function add()
.add()
uses both a
and b
, even though those functions have finished
executing. That's the **closure** in action!
ƒ add()
[[Scopes]]:
0: Closure (parent) {b: 6}
1: Closure (outer) {a: 4}
2: Script {add1: ƒ}
3: Global {...}
Definition:
Every method is a function, but not every function is a method.
Example:
const maths = {
E: 2.718281828459045,
add: function (a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
square(a) {
return a * a;
},
cube(a) {
return a * a * a;
}
};
// Usage
console.log(maths.add(2, 3)); // 5 (method call)
console.log(maths.square(4)); // 16 (method call)
Output:
5
16
this
keyword.this
is needed.