skip to Main Content

I want to create a Javascript function based on the state of a variable at that time, and when the variable changes, the function should not change. Like I want something where like:

let x = "A";
function f() {
  ????
}
x = "B";
f(); // Prints A, not B.

Neither of these below worked:

function f() {
  console.log(x);
}
function f() {
  let y = x + "";
  console.log(y);
}

These worked but I am worried that they access memory after it has been freed:

function g(y) {
  return () => {
    console.log(y);
  };
}
let f = g(x);
function g() {
  let y = x + "";
  return () => {
    console.log(y);
  };
}
let f = g();

How do I do this right?

2

Answers


  1. You can use an IIFE:

    let x = "A";
    const f = (() => {
      let y = x;
      return () => y;
    })();
    x = "B";
    console.log(f());
    Login or Signup to reply.
  2. The easiest way to achieve this programatically without having any memory leaks / global declarations (technically, depending where you declare let x), is to create a closure over a callback with the function in a following fashion:

    let x = "A";
    let f = (function(x) {
      return function() {
        console.log(x);
      };
    })(x);
    
    x = "B";
    f(); // Prints A

    The way this works, that it stores a reference as an argument and the callback accesses that reference for the inner (lambda) function instead of pointing reference to the let x declaration in memory.

    Note, the IIFE (self-invoked) function, at the end of the expression passing the argument

    })(x); // self-invoked 
    

    To anyone curious why this happens in the first place, it’s because JavaScript compiler employs hoisting, which moves declarations up so they are not in the order it may appear to a human eye in the code snipping and the function in the OP’s question points to a memory reference which already is changed by the statement x = 'B'

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search