This page looks best with JavaScript enabled

Shortcuts to variable assignments in Javascript

 ·   ·  ☕ 2 min read

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 -

1
2
3
let i = 0;
let j = 0;
let k = 0;

Or, you can instead do -

1
2
// prettier-ignore
let i = j = k = 0;

Initialize variables to different values

It is quite common to assign different values during initialization..

1
2
3
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.

1
2
// prettier-ignore
let i = 0,  j = 1,  k = 2;

But, there is also a better way.

1
2
3
4
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 -

1
2
3
4
let x = 4;
let y = 2;
let sum;
sum = x + y;

The cool way -

1
2
3
4
// 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 -

1
2
3
4
5
6
let j = 5000;
for (let i = 0; i < 100; i++) {
  // do something important

  if (something(i) > j - i) break;
}

And, the cool way -

1
2
3
4
5
for (let i = 0, j = 5000; i < 100; i++) {
  // do something important

  if (something(i) > j - i) break;
}
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things