DEV Community

Cover image for 16 useful TypeScript and JavaScript shorthands to know
Matt Angelosanto for LogRocket

Posted on • Updated on • Originally published at blog.logrocket.com

16 useful TypeScript and JavaScript shorthands to know

Written by Ibiyemi Adewakun✏️

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 16 common TypeScript and JavaScript shorthands. We will also explore examples of how to use these shorthands.

Read through these useful JavaScript and TypeScript shorthands or navigate to the one you’re looking for in the list below:

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]
Enter fullscreen mode Exit fullscreen mode

The following example demonstrates a traditional if…else statement and its shorthand equivalent using the ternary operator:

// Longhand
const mark = 80

if (mark >= 65) {
  return "Pass"
} else {
  return "Fail"
}

// Shorthand
const mark = 80

return mark >= 65 ? "Pass" : "Fail"
Enter fullscreen mode Exit fullscreen mode

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.

The following example demonstrates how to use short-circuit evaluation:

// Longhand
let str = ''
let finalStr

if (str !== null && str !== undefined && str != '') {
  finalStr = str
} else {
  finalStr = 'default string'
}

// Shorthand
let str = ''
let finalStr = str || 'default string' // 'default string
Enter fullscreen mode Exit fullscreen mode

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. Here are two examples of the nullish coalescing operator:

// Example 1
// Longhand
let str = ''
let finalStr

if (str !== null && str !== undefined) {
  finalStr = 'default string'
} else {
  finalStr = str
}

// Shorthand
let str = ''
let finaStr = str ?? 'default string' // ''

// Example 2
// Longhand
let num = null
let actualNum

if (num !== null && num !== undefined) {
  actualNum = num
} else {
  actualNum = 0
}

// Shorthand
let num = null
let actualNum = num ?? 0 // 0
Enter fullscreen mode Exit fullscreen mode

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 backticks and variables in ${} within those strings.

The example below demonstrates how to use template literals to perform string interpolation:

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

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

// Shorthand
const fullStr = `${name} loves ${hobby}`
Enter fullscreen mode Exit fullscreen mode

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:

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

// Shorthand
const x = 8
const y = 10
const obj = { x, y }
Enter fullscreen mode Exit fullscreen mode

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.

See an example of optional chaining in action below:

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
Enter fullscreen mode Exit fullscreen mode

Object destructuring

Besides the traditional dot notation, another way to read the values of an object is by destructuring the object’s values into their own variables.

The following example demonstrates how to read the values of an object using the traditional dot notation compared to the shorthand method using object destructuring.

const obj = {
  x: {
    y: 1,
    z: 2
  },
  other: 'test string'
}

// Longhand
console.log('Value of z in x: ', obj.x.z)
console.log('Value of other: ', obj.other)

// Shorthand
const {x, other} = obj
const {z} = x

console.log('Value of z in x: ', z)
console.log('Value of other: ', other)
Enter fullscreen mode Exit fullscreen mode

You can also rename the variables you destructure from the object. Here’s an example:

const obj = {x: 1, y: 2}
const {x: myVar} = object

console.log('My renamed variable: ', myVar) // My renamed variable: 1
Enter fullscreen mode Exit fullscreen mode

Spread operator

The spread operator is used to access the content of arrays and objects. You can use the spread operator to replace array functions, like concat, and object functions, like object.assign.

Review the examples below to see how the spread operator can be used to replace longhand array and object functions.

// Longhand
const arr = [1, 2, 3]
const biggerArr = [4,5,6].concat(arr)

const smallObj = {x: 1}
const otherObj = object.assign(smallObj, {y: 2})

// Shorthand
const arr = [1, 2, 3]
const biggerArr = [...arr, 4, 5, 6]

const smallObj = {x: 1}
const otherObj = {...smallObj, y: 2}
Enter fullscreen mode Exit fullscreen mode

Object loop shorthand

The traditional JavaScript for loop syntax is as follows:

for (let i = 0; i < x; i++) {  }
Enter fullscreen mode Exit fullscreen mode

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

The examples below demonstrate these object loop shorthands in action:

// 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]}`)
}
Enter fullscreen mode Exit fullscreen mode

Array.indexOf shorthand using the bitwise operator

We can look up the existence of an item in an array using the Array.indexOf method. This method returns the index position of the item if it exists in the array and returns -1 if it does not.

In JavaScript, 0 is a falsy value while numbers less than or greater than 0 are considered truthy. Typically, this means we need to use an if…else statement to determine if the item exists using the returned index.

Using the bitwise operator ~ instead of an if…else statement allows us to get a truthy value for anything greater than or equal to 0.

The example below demonstrates the Array.indexOf shorthand using the bitwise operator instead of an if…else statement:

const arr = [10, 12, 14, 16]

const realNum = 10
const fakeNum = 20

const realNumIndex = arr.indexOf(realNum)
const noneNumIndex = arr.indexOf(fakeNum)

// Longhand
if (realNumIndex > -1) {
  console.log(realNum, ' exists!')
} else if (realNumIndex === -1) {
  console.log(realNum, ' does not exist!')
}

if (noneNumIndex > -1) {
  console.log(fakeNum, ' exists!')
} else if (noneNumIndex === -1) {
  console.log(fakeNum, ' does not exist!')
}

// Shorthand
console.log(realNum + (~realNumIndex ? ' exists!' : ' does not exist!')
console.log(fakeNum + (~noneNumIndex ? ' exists!' : ' does not exist!')
Enter fullscreen mode Exit fullscreen mode

Casting values to Boolean with !!

In JavaScript, we can cast variables of any type to a Boolean value using the !![variable] shorthand. See an example of using the !! [variable] shorthand to cast values to Boolean:

// Longhand
const simpleInt = 3
const intAsBool = Boolean(simpleInt)

// Shorthand
const simpleInt = 3
const intAsBool = !!simpleInt
Enter fullscreen mode Exit fullscreen mode

Arrow/lambda function expression

Functions in JavaScript can be written using arrow function syntax instead of the traditional expression that explicitly uses the function keyword. Arrow functions are similar to lambda functions in other languages.

Take a look at this example of writing a function in shorthand using an arrow function expression:

// Longhand
function printStr(str) {
  console.log('This is a string: ', str)
}
printStr('Girl!')

// Shorthand
const printStr = (str) => {
  console.log('This is a string: ', str)
}
printStr('Girl!')

// Shorthand TypeScript (specifying variable type)
const printStr = (str: string) => {
  console.log('This is a string: ', str)
}
printStr('Girl!')
Enter fullscreen mode Exit fullscreen mode

Implicit return using arrow function expressions

In JavaScript, we typically use the return keyword to return a value from a function. When we define our function using arrow function syntax, we can implicitly return a value by excluding braces {}.

For multiline statements, such as expressions, we can wrap our return expression in parentheses ().

The example below demonstrates the shorthand code for implicitly returning a value from a function using an arrow function expression:

// Longhand
function capitalize(name) {
  return name.toUpperCase()
}

function add(numA, numB) {
  return numA + numB
}

// Shorthand
const capitalize = (name) => name.toUpperCase()

const add = (numA, numB) => (numA + numB)

// Shorthand TypeScript (specifying variable type)
const capitalize = (name: string) => name.toUpperCase()

const add = (numA: number, numB: number) => (numA + numB)
Enter fullscreen mode Exit fullscreen mode

Double bitwise NOT operator

In JavaScript, we typically access mathematical functions and constants using the built-in Math object. However, some functions have useful shorthands that allow us to access the function without referencing the Math object.

For example, applying the bitwise NOT operator twice ~~ allows us to get the Math.floor() of a value.

Review the example below to see how to use the double bitwise NOT operator as a Math.floor() shorthand:

// Longhand
const num = 4.5
const floorNum = Math.floor(num) // 4

// Shorthand
const num = 4.5
const floorNum = ~~num // 4
Enter fullscreen mode Exit fullscreen mode

Exponent power shorthand

Another mathematical function with a useful shorthand is the Math.pow() function. The alternative to using the built-in Math object is the ** shorthand.

The example below demonstrates this exponent power shorthand in action:

// Longhand
const num = Math.pow(3, 4) // 81

// Shorthand
const num = 3 ** 4 // 81
Enter fullscreen mode Exit fullscreen mode

TypeScript constructor shorthand

There is a shorthand for creating a class and assigning values to class properties via the constructor in TypeScript. When using this method, TypeScript will automatically create and set the class properties.

This shorthand is exclusive to TypeScript alone and not available in JavaScript class definitions.

Take a look at the example below to see the TypeScript constructor shorthand in action:

// Longhand
class Person {
  private name: string
  public age: int
  protected hobbies: string[]

  constructor(name: string, age: int, hobbies: string[]) {
    this.name = name
    this.age = age
    this.hobbies = hobbies
  }
}

// Shorthand
class Person {
  constructor(
    private name: string,
    public age: int,
    protected hobbies: string[]
  ) {}
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

These are just a few of the most commonly used JavaScript and TypeScript shorthands. Remember, using shorthand code is not always the best option; what is most important is writing clean and understandable code that other developers can read easily. What are your favorite JavaScript or TypeScript shorthands? Share them with us in the comments!


LogRocket: Debug JavaScript errors more easily by understanding the context

Debugging code is always a tedious task. But the more you understand your errors the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to find out exactly what the user did that led to an error.

Viewing JavaScript Errors in LogRocket

LogRocket records console logs, page load times, stacktraces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

Try it for free.

Top comments (1)

Collapse
 
tomford profile image
tomford51 • Edited

Very helpful tips, thank you for your help. I myself study Java and I know that this is not an easy task. But I think it's worth the time and effort because IT professionals are highly valued. For quick learning, I can recommend a site programmingassignment.net/javascri... I have already asked for help, they will help you learn Java faster as you will have an individual expert working with you, I think this is the most effective learning method