Is it possible to change variable value inside this function?

42 Views Asked by At

Is it possible to change the value of p inside the mf function via the call to up function passing it the p variable?

Theoretically it should be possible because javascript passes references of variables to functions, I think, by default

function up(p){
    p++;
    console.log('p from up function: ' + p);
}

function mf(){
    let p = 15;
    console.log('p from mf function: ' + p);
    return () => {
        console.log('p from arrow function before: ' + p);
        up(p);
        console.log('p from arrow function after: ' + p);
    }
}

let tf = mf()
tf()

After the call to tf() function I expected it to increase the value of p inside mf function but every time up function is receiving the same value of p that is 15

1

There are 1 best solutions below

0
Andrew Parks On BEST ANSWER

All you need to do is to put p into an object, and pass the object.

This is sometimes known as the "value holder" pattern.

function up(o){
  o.p++;
  console.log('p from up function: ' + o.p);
}

function mf(){
  let o = {p: 15};
  console.log('p from mf function: ' + o.p);
  return () => {
    console.log('p from arrow function before: ' + o.p);
    up(o);
    console.log('p from arrow function after: ' + o.p);
  }
}

let tf = mf()
tf()