Oleg Zinchenko
Oleg Zinchenko

Reputation: 631

Where does the below function get parameters from?

Function getFunc is not passed a parameter, why is this code working ?

function getFunc() {
    const a = 7;

    return b => {
        console.log(a+b);
    } }

const f = getFunc();

f(5); //12

Upvotes: 4

Views: 137

Answers (3)

Oleksandr Kovpashko
Oleksandr Kovpashko

Reputation: 800

It's called closure.

In JavaScript, the code inside functions has access to the variables defined inside this function and to variables defined in all parent functions. If you refer to a variable in the child function that's defined in the parent function and then you return child function JavaScript will preserve variables from the parent functions and they will be available in returned functions.

In your example, you're returning child function

b => {
    console.log(a+b);
}

from getFunc function so child function still has access to the variable a defined in parent function. When you execute f(5) child function executes 7 + 5 expression and you get 12 in the console.

Upvotes: 2

Dmytro Huz
Dmytro Huz

Reputation: 1554

function getFunc() {
const a = 7;

return function(b) { //it is more clear syntax
    console.log(a+b);
} }

const f = getFunc(); // here we have a function wich get 'b' parameter

f(5); //here we call this function and pass 5 as a 'b' parameter

Upvotes: 1

Prodigle
Prodigle

Reputation: 1797

getFunc returns the anonymous function

b =>{
  console.log(a+b);
}

so when you make a call to getFunc you're really calling console.log(7+parameter)

Upvotes: 2

Related Questions