JavaScript: Closures and Methods vs Functions

1. Closures in JavaScript

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
    

What's happening here?

Console Debug Output:

ƒ add()
[[Scopes]]:
    0: Closure (parent) {b: 6}
    1: Closure (outer) {a: 4}
    2: Script {add1: ƒ}
    3: Global {...}
    

2.. Methods vs Functions

Definition:

Important Rule:

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
    

Key Points to Remember: