Thomas
Thomas

Reputation: 458

How to create variables that hold variables

I think this is a simple one, and it may even have been asked previously, but I don't know what keywords to use to do a search. I believe that variables are strings and can only be strings, so even my question is a poor one, but I want to figure out a good way to do some math.

We start with something simple, like:

var a=0, b=a+1
console.log(a,b) // yields 0,1

But I then want to be able to update a later in the code and have it automatically update b, so if later I set:

a=1
console.log(a,b) // now yields 1,2

The goal being the updated b without having to tell the code that b=a+1 a second time (or hundreds of times, as this is a lot of math I am playing with).

Upvotes: 4

Views: 461

Answers (4)

3limin4t0r
3limin4t0r

Reputation: 21110

Instead of using a variable you could use an object with a getter and setter.

const obj = {
  a: 0,
  get b() { return this.a + 1 },
  set b(value) { this.a = value - 1 },
};

console.log(obj);
obj.a = 10;
console.log(obj);
obj.b = 20;
console.log(obj);

If you never plan to set b, then you can omit the setter.

Upvotes: 3

Ankit Jaishwal
Ankit Jaishwal

Reputation: 526

You can create a function to increment both the values.

const func= () => {
  a++;
  b++;
};

And then you can call the function each time you have to increment values. If you have to increment continuously for a fixed number of times then call the function inside a loop.

Upvotes: 1

Gabriel Lupu
Gabriel Lupu

Reputation: 1447

I would use a function for b instead and call it whenever is needed.

let a = 1;
const b = () => a + 1;
console.log(b()); // prints 2
a = 10;
console.log(b()); // prints 11

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370619

Create a separate function that updates both variables. Then, whenever you want to modify them, call the method instead of reassigning the variables manually, for example:

var a = 0,
  b = a + 1;

const increment = () => {
  a++;
  b++;
};
increment();
increment();
console.log(a, b);

Upvotes: 2

Related Questions