Categories
JavaScript JavaScript Basics

Handy JavaScript Shorthands

Spread the love

With the latest versions of JavaScript, the language has introduced more syntactic sugar. In this article, we’ll look at handy shortcuts that are easy to read from versions of JavaScript new and old.

In this article, we’ll look at the ternary operator, declaring multiple variables, arrow functions, default parameter values, and more.

Ternary Operator

We can write an if...else statement in a concise way by using the ternary operator.

Instead of writing:

const x = 20;
let grade;

if (x >= 50) {
  grade = "pass";
} else {
  grade = "fail";
}

We can write:

const x = 20;
let grade = (x >= 50) ? "pass" : "fail";

They both check if x is bigger than or equal to 50 then assign the string 'pass' if it’s true and fail otherwise.

We can also write nested if statement with the ternary operator as follows:

const x = 20;
let grade = (x >= 50) ? "pass" : (x >= 25) ? "good fail" : 'bad fail';

This is the same as:

const x = 20;
let grade;
if (x >= 50) {
  grade = "pass";
} else {
  if (x >= 25) {
    grade = "good fail";
  } else {
    grade = "bad fail";
  }
}

Setting Default Value

We can set a default value if a variable is falsy by writing:

let x;
let y = x || 10;

This is the same as:

let x;
let y;
if (x === undefined || x === null || x === 0 || x === '' || isNaN(x)) {
  y = 10;
}

Because x || 10 means that if x is falsy, which means that x is undefined, null, 0, empty string, or NaN, then we assign 10 to y, which is the same as:

if (x === undefined || x === null || x === 0 || x === '' || isNaN(x)) {
  y = 10;
}

Shorthand for Declaring Multiple Variables

We can declare multiple variables by writing:

let x = y = z = 5;

This is the same as writing:

let x = 5;
let y = 5;
let z = 5;

It works by first assigning 5 to z, then the value of z to y, and finally the value of y to x .

If Truthy Shorthand

A shorthand for checking if something is truthy is JavaScript, which is anything other than undefined, null, 0, empty string, or NaN, is the following:

if (x){
 console.log('x is truthy')
}

The code above checks if x is truthy, then we execute the console.log if it is.

For…Of Loop Shorthand

Since ES6, we can use the for...of loop to loop through variables in an array or array-like object, which includes things like Maps, Sets, the arguments object, generators, iterators, and any object with the [Symbol.iterator] method.

We can write:

let fruits = ['apple', 'orange', 'grape'];
for (let fruit of fruits) {
  console.log(fruit);
}

This is cleaner than using a regular for loop with indexes, and it also works other iterable objects. For example, we can use it with generators:

let fruits = function*() {
  yield 'apple';
  yield 'orange';
  yield 'fruits';
}

for (let fruit of fruits()) {
  console.log(fruit);
}

Photo by Robin Mantz on Unsplash

Array.forEach

We can use the Array.forEach method to loop through an array, although it’s slower than loops.

To use it, we can write something like the following code:

let fruits = ['apple', 'orange', 'grape'];

fruits.forEach((fruit, index) => console.log(fruit));

Decimal Base Exponents

We can specify exponential numbers instead of writing out the whole number out with all the trailing zeroes.

For example, if we have:

1e0

for 1

1e1

for 10

1e2

for 100

1e3

for 1000 and so on.

Digit Separators

The latest browsers let us use an underscore to separate digits to make them easy to read. For example, we can write

100_000_000

for 100 million. Underscores can be placed anywhere we choose.

Object Property Shorthand

Instead of writing:

const foo = 1,
  bar = 2;
const obj = {
  foo: foo,
  bar: bar
};

We can write:

const foo = 1,
  bar = 2;
const obj = {
  foo,
  bar
};

The 2 pieces of code are exactly the same.

Arrow Functions

If an arrow function is only one line, then we don’t need the braces and we can return a value from it without using the return keyword.

For example:

() => 1

is the same as:

() => {
  return 1
}

We can use arrow functions if we don’t care about the value of this since arrow functions don’t change the this value inside the function.

Default Parameter Values

We can specify default parameter values in ES6. For example, we can write:

const add = (a = 1, b = 2) => {
  return a + b
}

This is the same as:

const add = (a, b) => {
  if (typeof a === 'undefined') {
    a = 1;
  }

  if (typeof b === 'undefined') {
    b = 1;
  }
  return a + b
}

The shorthands above are mostly from ES6. This version of JavaScript provides lots of handy shortcuts which lets us write code easier and reading just as easy.

for...of loop is very useful since it can loop through arrays and array-like objects. No other loops can do that.

Digit separators are more recent and available in the latest browsers only.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *