Return to blog

5 useful JavaScript shorthands

hero image for 5 useful JavaScript shorthands

1. Loop shorthand

If you write old school for-loops instead of using Lodash or other library, this might be very useful.

Longhand:

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

Shorthand:

for (let value of array) {
  console.log(value);
}

2. Decimal base exponents

This tip won't save your precious time to much, but allows you to write numbers with trailing zeros in more fancy way.

1e1 === 10
1e2 === 100
1e3 === 1000
1e4 === 10000
1e5 === 100000

3. Implicit return shorthand

Is it possible to make arrow function even more shorter? Let's take a look at this example:

Longhand:

dummyMultiply = value => { return value * value; }

Shorthand:

dummyMultiply = value => (value * value);
//or
dummyMultiply = value => value * value;

4. Default parameters

I think every developer knows this feature but let's utilize previous tip also.

Longhand:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}

Short(est)hand:

volume = (l, w = 3, h = 4 ) => (l * w * h);

5. Mandatory parameter shorthand

Let's try to use default parameters feature one more time. If parameter is not passed to function, JavaScript will set it as undefined... or we can assign default value (like in previous example) or something more complex.

Longhand:

foo = (bar) => {
  if (bar === undefined) {
    throw new Error('Missing parameter!');
  }
  return bar;
}

Shorthand:

mandatory = () => {
  throw new Error('Missing parameter!');
}

foo = (bar = mandatory()) => {
  return bar;
}

I can easily imagine, that it can be utilized also to log something in application (like missing parameter). Nice, huh?

As a reliable software company we’re focused on delivering the best quality IT services. However, we’ve discovered that programming skills give us a very particular opportunity...

.eco profile for codetain.eco

Reach Us

65-392 Zielona Góra, Poland

Botaniczna 70

© 2015-2024 Codetain. All rights reserved.

cnlogo