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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With