Skip to content
Advertisement

Functions and parenthesis in Javascript

I don’t understand how all those f() function work, can someone explain why it prints two ‘1’, I know it prints ‘1’ for every ‘()’ after f(f), but I don’t know why.

function f(y) {
  let x = y;
  var i = 0;
  return () => {
    console.log(++i);
    return x(y);
  };
}
f(f)()();

And why does the ‘i’ doesn’t increase?

Thank you.

Advertisement

Answer

function f(y) {
  let x = y;
  var i = 0;
  return () => {
    console.log(++i);
    return x(y);
  };
}
f(f)()();

is equivalent to

function f() {
  var i = 0;
  return () => {
    console.log(++i);
    return f();
  };
}
const t1 = f();
const t2 = t1();
t2();

is equivalent to

function f() {
  var i = 0;
  return () => {
    console.log(++i);
  };
}
const t1 = f();
t1();
const t2 = f();
t2();

If you did call each of t1 or t2 multiple times instead of just once, you’d increment the i from the respective closure some more. But if you instead just chain them, they call f again and initialise a new var i = 0 for a different closure.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement