Lukas
Lukas

Reputation: 151

Functions implicitly taking in arguments

I am just curious as to why the function below works perfectly fine, although in its definition we can't see any arguments defined?

This does not seem to be intuitive to a starting JS developer.

const add = () => {
    return num => {
        const result = num + 10;
        return `Calculated! ${result}`;
    };
};

const addFn = add()
console.log(addFn(5)) // Calculated! 15

Upvotes: 2

Views: 39

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50787

You're partially right. add takes no arguments. If you supply any, they will be ignored.

But when you call add, you get back the function

num => {
    const result = num + 10;
    return `Calculated! ${result}`;
}

which might be easier to recognize as a function if you wrapped its single argument in parentheses:

(num) => {
    const result = num + 10;
    return `Calculated! ${result}`;
}

This new function takes (presumably) a number, adds 10 to it, and returns a formatted string including that result.

So this:

const addFn = add()

simply assigns the value of addFn as this function returned by add (), namely the function we describe above.

When we call it with 5, it returns that formatted string involving the result of 10 + 5.

Does that make it any clearer?

Upvotes: 6

Related Questions