Simultaneously Increment Two Variables in JavaScript
- 1 minute read
Did you know that you can update two variables at the same time in JavaScript?
In some contexts, one-liners that shorten multi-line snippets can be very useful.
Here is an example of adding a number to two variables:
numOne += 1;
numTwo += 1;
That snippet can be shortened to this one-liner, while maintaining the exact same behavior:
numOne += -numTwo + (numTwo += 1);
The caveat here is that numOne
and numTwo
must be incremented by the same number.
However, you can use any number, not just 1
.
This one-liner can be slightly modified to work for subtraction, too:
numOne -= -numTwo + (numTwo += 1);
The above snippet will subtract 1
from both numOne
and numTwo
.
Conclusion
Anyway, this is just one of the many simple tricks you can use in JavaScript to shorten otherwise multi-line operations into one line.
Enjoy!