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
You can use an IIFE:
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: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
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'