Search code examples
javascriptclosuresiife

why this closure and IIFE dont works?


Why this code dont print i and j variables?

(function f() {
  let i = 1;
  let j = 2;
  return () => {
    console.log(i);
    console.log(j);
  }
})()

I know, i know... this code yes, works:

let f = () => {
  let i = 1;
  let j = 2;
  return () => {
    console.log(i);
    console.log(j);
  }
}

f()();

Yes, the last code works, but I what to know why the first code doesn't works

Thanks a lot


Solution

  • You are returning a function (return () => {}) from the function but not calling it. You could simply just log the values in the function without returning a new function.

    (function f() {
      let i = 1;
      let j = 2;
      console.log(i);
      console.log(j);
    })();

    Or call it like this.

    (function f() {
      let i = 1;
      let j = 2;
      return () => {
        console.log(i);
        console.log(j);
      }
    })()();