Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create variables that hold variables

Tags:

javascript

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).

like image 836
Thomas Avatar asked Mar 02 '23 23:03

Thomas


1 Answers

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.

like image 66
3limin4t0r Avatar answered Mar 11 '23 23:03

3limin4t0r