I need help with closures and functions!

So I can’t understand what happens under the hood with my code.

function expression(number, operation) {
  if(!operation) {
    return number;
  } else {
    return operation(number);
  }

}

function five(oper) { return expression(5, oper)}

function seven(oper) { return expression(7, oper)}

function plus(x) {
  return function(y) {
     return x + y;
  }
}

let rezultat = seven(plus(five()))

I’ll start with closure. Closure is a function which remebers it’s outer function’s lexical environment. so that means closure(inner function) has reference to it’s outer function’s variables.

function plus(x) {
  return function(y) {
     return x + y;
  }
}

In above code function(y)... will remeber variables(here ‘x’) defined in outer function plus(x)..

suppose I write,
let a = plus(2); // this will assign ‘2’ to variable ‘x’ and than return inner function which remebers (has reference) to it’s outer function’s lexical environment.
so now "a" stores 'function(y)..'
now if I write a(3) , this will call that stored inner function , where it tries to access x and y , now y’s value we have passed ( 3 ) , and as it doesn’t find x , it starts searching for x in it’s outer lexical environment, and it finds it there with value 2.

so calling a(3) returns 5.
same way let b = plus(4) ; b(3) will return 7.

now if I break your code for simplicity as below

let rezultat = seven(plus(five()))

five() - returns 5.
let rezultat = seven(plus(5)) - replacing here with return value
plus(5) - returns inner function which remebers it’s outer function’s variable x = 5.
let rezultat = seven(innerFunction) - here I am writing inner function for sake of understanding

now , seven(innerFunction) - will call expression(7, innerFunction) and than return it’s value

inside expression(7, innerFunction) , else part will be executed
innerFunction(7) - returns 5(value remebered ) + 7 = 12

so, `` seven(innerFunction)` - returns 12
so , value of rezultat will be 12

1 Like

Looks like an exercise in confusion!
Maybe start with this:

function nPlusTen(n) { return n+10; }
function nPlusOper(number, operation) { 
  if(!operation) return number;
  else return operation(number);
}
console.log(nPlusTen); // the function
console.log(nPlusTen(3)); // the function executed

console.log(nPlusOper); // the function
console.log(nPlusOper(3)); // the function executed 
console.log(nPlusOper(3, nPlusTen)); // the function executed
1 Like

Thanks a lot, now it’s clear and understood :relaxed: