About this App

Lorem ipsum dolor sit amet, consecte tuer adipiscing elit, sed diam tincidunt ut laoreet dolore magna aliq.

Address

302 2nd St
Brooklyn, NY 11215, USA
40.674386 – 73.984783

Folow us on social

5 useful JavaScript shorthands

The best developers are smart but lazy developers. Why? Because lazy developer will always find a way to do something in a shorter way. And today we’re going to take a look at some shorthand coding techniques in JavaScript language (with ES6).

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;
}

Shorthand:

volume = (l, w = 3, 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 [i]undefined[/i]… 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?

Post a Comment