1

I want to create callback function with some parameters, but I want that one of the values within never change and be set when the function is created!

P.e.

let a = 2;
let y = (b) => { let staticValue = a; return staticValue * b; }

y(1) => 2 -> OK

then

a = 3
y(1) => 3 -> Not OK -> I want the function to have the original value of a.

I know, this happens because the variable a is only evaluated when the function is called. But is there any workaround?

3
  • Why don't you just use b * 2 or similar if you really want to make it static ? Commented Nov 24, 2020 at 13:20
  • 1
    Possible with localStorage and all that mess - but why bother? Just hard code the value into the function Commented Nov 24, 2020 at 13:21
  • Yes, I need to "remember" the original value. Commented Nov 24, 2020 at 13:23

4 Answers 4

4

You can accomplish this with what is called an IIFE (immediately invoked function expression)

let a = 2;
const y = (staticValue => b => staticValue * b)(a);

a = 44;
console.log(y(1));

What's happening here is that you have two functions. The first one, staticValue => ... is immediately invoked, and staticValue is given the value of a. Since a is given as an argument of the IIFE, once the function is invoked staticValue won't change, even if the value of a is changed.

The return value of the first function is a second function, b=> ....

Sign up to request clarification or add additional context in comments.

Comments

2
let a = 2
let makeY = () => {
  let staticValue = a;
  return (b)=> staticValue * b;
}
let y = makeY();

or

let a = 2
let y = ((staticValue, b) => {
  return staticValue * b;
}).bind(null, a)

Comments

2

you can use closure

function first (a) {
    function second (b) {
          return a * b;    
    }
    return second;
}

let x = first(2)  // the inner function second will close around the variable a which is 2 in this case

console.log(x(3))

let y = first(5)  // the inner function second will close around the variable a which is 5 in this case

console.log(y(3))

Comments

1

I think you could apply a Functional programming approach.

const getYFn = (a , b) => {
  return a * b;
}

const a = 2

const y = getYFn.bind(null, a);

// the constant y now is a function that partially applied first param
console.log(y(1)); // 2
console.log(y(3)); // 6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.