You don’t have to see assigning values to variables as a chore. There are exciting ways to do those assignments - here are some shorthand ways.
Initialize to same value
You can initialize variables like so -
let i = 0;
let j = 0;
let k = 0;
Or, you can instead do -
// prettier-ignore
let i = j = k = 0;
Initialize variables to different values
It is quite common to assign different values during initialization..
let i = 0;
let j = 1;
let k = 2;
.. so why not have a shorthand for that? Just do assignment using the previous way of combining declarations.
// prettier-ignore
let i = 0, j = 1, k = 2;
But, there is also a better way.
let [l, j, k] = [0, 1, 2];
console.log(l, j, k);
// 0 1 2
Assign + operate
Do assignments while doing important operations.
Traditional way -
let x = 4;
let y = 2;
let sum;
sum = x + y;
The cool way -
// prettier-ignore
let x = 4, y = 2, sum = x + y;
console.log("sum: ", sum);
// 6
Assign in loops
You can assign values when initializing loops.
The traditional way -
let j = 5000;
for (let i = 0; i < 100; i++) {
// do something important
if (something(i) > j - i) break;
}
And, the cool way -
for (let i = 0, j = 5000; i < 100; i++) {
// do something important
if (something(i) > j - i) break;
}