Useful TypeScript and JavaScript shorthands to know

What Is Quantum Computing?
6th May 2022
Xcode 13.4
Xcode 13.4
18th May 2022
What Is Quantum Computing?
6th May 2022
Xcode 13.4
Xcode 13.4
18th May 2022

JavaScript and TypeScript share a number of useful shorthand alternatives for common code concepts. Shorthand code alternatives can help reduce lines of code, which is something we typically strive for.

In this article, we will review common TypeScript and JavaScript shorthands. We will also explore examples of how to use these shorthands.

JavaScript and TypeScript shorthands

Using shorthand code is not always the right decision when writing clean and scalable code. Concise code can sometimes be more confusing to read and update. It is important that your code is legible and conveys meaning and context to other developers.

Our decision to use shorthands must not be to the detriment of other desirable characteristics of code. Keep this in mind when using the following shorthands for expressions and operators in JavaScript and TypeScript.

All shorthands available in JavaScript are available in the same syntax in TypeScript. The only slight difference is in specifying the type in TypeScript. However, the TypeScript constructor shorthand is exclusive to TypeScript.

Ternary operator

The ternary operator is one of the most popular shorthands in JavaScript and TypeScript. It replaces the traditional if…else statement. Its syntax is as follows:

[condition] ? [true result] : [false result]
Example : const result = mark >= 65 ? "Pass" : "Fail"

Short-circuit evaluation

Another way to replace an if…else statement is with short-circuit evaluation. This shorthand uses the logical OR operator || to assign a default value to a variable when the intended value is falsy.

Example :
let str = ''
let finalStr = str || 'default string' // 'default string

Nullish coalescing operator

The nullish coalescing operator ?? is similar to short-circuit evaluation in that it is used to assign a default value to a variable. However, the nullish coalescing operator only uses the default value when the intended value is also nullish.

In other words, if the intended value is falsy but not nullish, it will not use the default value.

Example : 
let num = null
let actualNum = num ?? 0 // 0

Template literals

With JavaScript’s powerful ES6 features, we can use template literals instead of using + to concatenate multiple variables within a string. To use template literals, wrap your strings in `` and variables in ${} within those strings.

Example : 
const name = 'Iby'
const hobby = 'to read'

// Longhand
const fullStr = name + ' loves ' + hobby // 'Iby loves to read'

// Shorthand
const fullStr = `${name} loves ${hobby}`

Object property assignment shorthand

In JavaScript and TypeScript, you can assign a property to an object in shorthand by mentioning the variable in the object literal. To do this, the variable must be named with the intended key.

See an example of the object property assignment shorthand below:

Example : 

// Longhand
const obj = {
  x: 1,
  y: 2,
  z: 3
}

// Shorthand
const x = 8
const y = 10
const obj = { x, y }

Optional chaining

Dot notation allows us to access the keys or values of an object. With optional chaining, we can go a step further and read keys or values even when we are not sure whether they exist or are set. When the key does not exist, the value from optional chaining is undefined.

Example :

const obj = {
  x: {
    y: 1,
    z: 2
  },
  others: [
    'test',
    'tested'
  ] 
}

// Longhand
if (obj.hasProperty('others') && others.length >= 2) {
  console.log('2nd value in others: ', obj.others[1])
}

// Shorthand
console.log('2nd value in others: ', obj.others?.[1]) // 'tested'
console.log('3rd value in others: ', obj.others?.[2]) // undefined

Object loop shorthand

The traditional JavaScript for loop syntax is as follows:

for (let i = 0; i < x; i++) { … }

We can use this loop syntax to iterate through arrays by referencing the array length for the iterator.

There are three for loop shorthands that offer different ways to iterate through an array object:

  • for…of to access the array entries
  • for…in to access the indexes of an array and the keys when used on an object literal
  • Array.forEach to perform operations on the array elements and their indexes using a callback function

Please note that Array.forEach callbacks have three possible arguments, which are called in this order:

  • The element of the array for the ongoing iteration
  • The element’s index
  • A full copy of the array

Example :

// Longhand
const arr = ['Yes', 'No', 'Maybe']

for (let i = 0; i < arr.length; i++) {
  console.log('Here is item: ', arr[i])
}

// Shorthand
for (let str of arr) {
  console.log('Here is item: ', str)
}

arr.forEach((str) => {
  console.log('Here is item: ', str)
})

for (let index in arr) {
  console.log(`Item at index ${index} is ${arr[index]}`)
}

// For object literals
const obj = {a: 1, b: 2, c: 3}

for (let key in obj) {
  console.log(`Value at key ${key} is ${obj[key]}`)
}