0
function test(n) {
    let y = 0
    let x = y / 2

    while (y < n) {
        console.log('add');
        y++;
    }
    console.log(y);
    console.log(x);
}
test(6);
//x prints out 0 instead of 3

x is supposed to change as y changes. How do I keep these variables synchronized?

  • Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – zombiedoctor Oct 08 '19 at 19:36

4 Answers4

1

If you want to keep the variables in sync all the time, you can create an object having y and a getter method for x which returns the value dependent on current value of y

let obj = {
  y: 0,
  get x() {
    return this.y / 2;
  }
};
function test(n) {
  while (obj.y < n) {
    console.log("add");
    obj.y++;
  }
  console.log(obj.y);
  console.log(obj.x);
}
test(6);
AZ_
  • 3,094
  • 1
  • 9
  • 19
0

There's nothing that does that automatically, you need to do it yourself.

    while (y < n) {
        console.log('add');
        y++;
    }
    x = y/2;

If the second variable is always the same function of the first variable, are you sure you need two variables?

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

In general, your best option will likely be to use a function to calculate the value when it's called, particularly if you're doing inexpensive calculations. Think of it as an algebraic expression.

Consider the following:

function x(y) {
  return y / 2
}

function test(n) {
    let y = 0

    while (y < n) {
        console.log('add');
        y++;
    }
    console.log(y);
    console.log(x(y));
}
test(6);
Christopher
  • 856
  • 9
  • 16
0

If x is always half of y, then why do you need X?

Vishal Khare
  • 41
  • 1
  • 5