TypeScript and JavaScript have several useful shorthand alternatives for basic coding. Shorthand code can assist you in reducing lines of code and make code look pretty. In addition, shorthand code can also make your code more readable and easier to follow.
We’ll look at various TypeScript and JavaScript shorthands methods in this post. We’ll also look at examples of how to utilize these shorthands in practice.
When creating clean, scalable code, it is not always best to use shorthand code. Concise code may indeed be difficult to read and update. Your code must be understandable, meaningful, and contextual to other developers.
But also, there are some advantages to using shorthand code. In some cases, it can reduce the time you spend coding. In other cases, it can make your code more readable.
Some general benefits of using shorthand methods include:
Shorthand is an abbreviation for longer pieces of code. Sometimes, it can replace multiple lines of code with a single line. In other cases, it can shorten the length of a line of code.
Shorthand can be used for various things, including:
Finally, we must not use shorthands at the expense of other desirable code qualities. Keep in mind when using the following shorthands for expressions and operators in JavaScript and TypeScript.
All of JavaScript’s shorthands are available in the same syntax as TypeScript. The only difference is to specify the type in TypeScript. However, the TypeScript constructor shorthand is only available in TypeScript.
When your code receives data, that must be handled in numerical format, even though it comes in string form. It’s not a huge problem; we can perform a rapid conversion.
// Longhand const num1 = parseInt('90') const num2 = parseFloat('80.05') // Shorthand const num1 = +'90' // converts to int data type const num2 = +'80.05' // converts to float data type
The ternary operator is a popular shorthand in JavaScript and TypeScript. It replaces the standard if…else statement. Its syntax is as follows:
[condition] ? [true result] : [false result]
The following example shows how a typical if…else statement might be expressed using the ternary operator:
// Longhand const a = 120 const b = 85 if (a > b) { return 'a is biggest' } else { return 'b is biggest' } // Shorthand const a = 120 const b = 85 return a > b ? 'a is biggest' : 'b is biggest'
With JavaScript’s powerful ES6 features, We can utilize template literals in place of the + operator to concatenate many variables into a string. To use template literals, wrap your strings in “ (backtick) and variables in ${} within them.
Here’s an example of string interpolation using template literals:
const first = 'Beau' const last = 'Jameson' // Longhand const welcomeMessage = first + ' ' + last + ', welcome to this world!' + '.' const db = 'http://' + host + ':' + port + '/' + database // Shorthand const welcomeMessage = `${first} ${last}, welcome to this world!.` const db = `http://${host}:${port}/${database}`
You can also construct multiline strings without using \n by using template literals. For example:
// Shorthand const person = 'Jameson' const requirement = 'to play Cricket!' const fullString = `${person} wants ${requirement}. He also wants to play Football!`
We can get at the keys and values of an object using dot notation. We can go a step further with optional chaining when we’re unsure if particular keys or values exist or are set. The value of optional chaining is undefined when the key does not exist.
Take a look at the following example to see how optional chaining works:
const list = { obj: { P: 1, S: 2 }, others: ['value', 'values', 'test'] } // Longhand if (list.hasProperty('others') && others.length >= 3) { console.log('others 2nd item is: ', list.others[1]) } // Shorthand console.log('others 3rd item is: ', list.others?.[2]) // 'test' console.log('others 4th item is: ', list.others?.[3]) // undefined
The if statement may be used to provide default values for function parameters. You can also define the default values inside the function declaration in ES6.
// Longhand function value(a, b, c) { if (b === undefined) b = 5 if (c === undefined) c = 2 return a * b * c } // Shorthand volume = (a, b = 5, c = 2) => a * b * c volume(6) //output: 60
The Math.pow() method is another important mathematical function with a helpful shorthand. The ** shorthand is an alternative to using the basic Math object.
This exponent power shorthand is demonstrated in the example below:
// Longhand const value = Math.pow(4, 4) // 256 // Shorthand const value = 4 ** 4 // 256
In JavaScript, functions can be defined using Arrow function syntax instead of the conventional expression that explicitly uses the function keyword. Arrow functions are similar to lambda functions in other languages.
Take a look at this function written in shorthand, using an arrow function expression:
// Longhand function fruits(str) { console.log('The fruits is', str) } fruits('Apple') // Shorthand const fruits = str => { console.log('The fruits is', str) } fruits('Apple') // Shorthand TypeScript (specifying variable type) const fruits = (str: string) => { console.log('The fruits is', str) } fruits('Apple')
Another approach to reading the values of an object is to destructure them into their variables, in addition to using the standard dot notation.
The following code sample illustrates the difference in readability between standard dot notation and object destructuring to access an object’s values.
const data = { list: { p: 1, s: 2 }, other: 'demo' } // Longhand console.log('Value of s in list: ', data.list.s) console.log('Value of other: ', data.other) // Shorthand const { list, other } = data const { s } = list console.log('Value of s in list: ', s) console.log('Value of other: ', other)
The object variables can also be renamed. Here’s a scenario:
const data = { u: 10, v: 27 } const { u: list } = data console.log('My renamed variable is: ', list) // My renamed variable: 10
Short-circuit evaluation is another approach to replace an if…else statement. When the intended value of a variable is falsy, This shorthand utilizes the logical OR operator || to set the default value of a variable.
This example shows how to use short-circuit evaluation:
// Longhand let string = '' let updatedString if (string !== null && string !== undefined && string != '') { updatedString = string } else { updatedString = 'Default string' } // Shorthand let string = '' let updatedString = string || 'Default string' // Default string
When we use the !! [variable] shorthand in JavaScript, we can convert variables of any type to a boolean value.
An example of using the !! [variable] shorthand to convert values to boolean is as follows:
// Longhand const int = 56 const intAsBool = Boolean(int) // Shorthand const int = 56 const intAsBool = !!int
A for loop is a function that iterates over or repeats a block of code. If you’ve ever had to write a find function in plain JavaScript, you’ve probably used this one. A new array function named find() was introduced in ES6.
Let’s look at an example of Array.find Shorthand:
// Longhand const pets = [ { type: 'Dog', name: 'Rio' }, { type: 'Cat', name: 'Karl' }, { type: 'Dog', name: 'Tommy' }, { type: 'Cat', name: 'Max' } ] function findDog(name) { for (let i = 0; i < pets.length; i++) { if (pets[i].type === 'Dog' && pets[i].name === name) { return pets[i] } } } // Shorthand fingPet = pets.find(pet => pet.type === 'Dog' && pet.name === 'Tommy') console.log(fingPet) // { type: 'Dog', name: 'Tommy' }
The spread operator … is a method for accessing the content of arrays and objects. You can use the spread operator to replace array functions, such as concat, and object functions, like Object.assign.
Explore how the spread operator can be used to replace longhand array and object operations; consider the following examples:
// Longhand const array = [7, 8, 9, 10] const listOfArray = [3, 4, 5, 6].concat(array) const smallArray = { x: 'Apple' } const bigArray = Object.assign(smallArray, { y: 'Orange' }) // Shorthand const array = [7, 8, 9, 10] const listOfArray = [3, 4, 5, 6, ...array] const smallArray = { x: 'Apple' } const bigArray = { ...smallArray, y: 'Orange' }
TypeScript has a shorthand for defining and assigning values to class properties in the constructor. When utilizing this approach, the class properties will be automatically created and set by TypeScript.
This shorthand is only available in TypeScript, not JavaScript class definitions.
Here’s an example of the TypeScript constructor shorthand works:
// Longhand class Employee { private name: string public age: int protected address: string[] constructor(name: string, age: int, address: string[]) { this.name = name this.age = age this.address = address } } // Shorthand class Employee { constructor( private name: string, public age: int, protected address: string[] ) {} }
The nullish coalescing operator ??, similar to short-circuit evaluation, allows you to set a default value for a variable. However, the nullish coalescing operator only uses the default value if the intended value is also nullish. In other words, it will not use the default value if the intended value is falsy but not nullish.
The following are two examples of the nullish coalescing operator:
// Example 1 // Longhand let string = '' let updatedString if (string !== null && string !== undefined) { updatedString = 'Default string' } else { updatedString = string } // Shorthand let string = '' let updatedString = string ?? 'Default string' // '' // Example 2 // Longhand let number = null let actualNumber if (number !== null && number !== undefined) { actualNumber = number } else { actualNumber = 0 } // Shorthand let number = null let actualNumber = number ?? 0 // 0
Using the Array.indexOf method, we can determine whether an item exists in an array. If the item is present, this method returns its index position; otherwise, it returns -1.
In JavaScript, the value 0 is false, while numbers less than or greater than 0 are considered true. We usually need to use an if…else statement to check whether the item exists using the returned index in this case.
We can use the bitwise operator ~ to get a true value for anything greater than or equal to 0 rather than an if…else statement.
The Array.indexOf method can also be used with a bitwise operator in place of an if…else statement in the example below:
const list = [3, 6, 9, 12, 15, 18, 21] const requiredNumber = 9 const fakeNumber = 13 const requiredNumberIndex = list.indexOf(requiredNumber) const fakeNumberIndex = list.indexOf(fakeNumber) // Longhand if (requiredNumberIndex > -1) { console.log(`Required number ${requiredNumber} is exists!`) } else if (requiredNumberIndex === -1) { console.log(`Required number ${requiredNumber} is does not exist!`) } if (fakeNumberIndex > -1) { console.log(`Fake number ${fakeNumber} is exists!`) } else if (fakeNumberIndex === -1) { console.log(`Fake number ${fakeNumber} is does not exist!`) } // Shorthand console.log( requiredNumber + (~requiredNumberIndex ? ' exists!' : ' does not exist!') ) console.log(fakeNumber + (~fakeNumberIndex ? ' exists!' : ' does not exist!'))
The return keyword can be used in JavaScript to indicate that a function should produce a value and then terminate. We can also implicitly return a value by omitting braces {} when we define our function using arrow function syntax.
We can surround a return statement with parentheses () when we use multiline statements, such as expressions.
The following example shows the shorthand code for returning a value from a function using an arrow function expression:
// Longhand function capitalize(xyz) { return xyz.toUpperCase() } function multiplication(numA, numB) { return numA * numB } // Shorthand const capitalize = xyz => xyz.toUpperCase() const multiplication = (numA, numB) => numA * numB // Shorthand TypeScript (specifying variable type) const capitalize = (xyz: string) => xyz.toUpperCase() const multiplication = (numA: number, numB: number) => numA * numB
The typical JavaScript for loop syntax is as follows:
for (let i = 0; i < x.length; i++) { ... }
This loop syntax can be used to iterate through arrays by referring to the array length of the iterator.
There are three for loop shorthands that can be used to iterate over an array object in different ways:
It’s important to remember that Array.forEach callbacks method has three possible arguments, which are called in this sequence:
Here are some examples of these object loop shorthands in action:
const list = ['Cricket', 'Football', 'Hockey', 'Tennis'] // Longhand for (let i = 0; i < list.length; i++) { console.log('List of match is: ', list[i]) } // Shorthand for (let eachMatch of list) { console.log('List of match is: ', eachMatch) } list.forEach(eachMatch => { console.log('List of match is: ', eachMatch) }) for (let index in list) { console.log(`Match at index ${index} is ${list[index]}`) } // For object literals const objList = { w: 0, x: 9, y: 27, z: 10 } for (let key in objList) { console.log(`Value at key ${key} is ${objList[key]}`) }
The Math object is used to call mathematical operators and constants in JavaScript. However, some functions have handy shorthands that allow us to utilize the process without referencing the Math object.
When applied twice ~~ to a value, the bitwise NOT operator returns the Math.floor() of that value.
As a Math.floor() shorthand, the double bitwise NOT operator is written as follows:
// Longhand const A = 9.5 const floorNumber = Math.floor(A) // 9 // Shorthand const A = 9.5 const floorNumber = ~~num // 9
In JavaScript and TypeScript, You can set shorthand property to an object by including the variable in the object literal. To do so, the variable must be named with the intended key.
The following is an example of the object property assignment shorthand:
// Longhand const array = { A: 7, B: 8, C: 9 } // Shorthand const A = 54 const B = 89 const array = { A, B }
Here are a handful of the most common JavaScript and TypeScript shorthands. Always keep in mind that shorthand code is not always the best solution; what matters most is writing clean and understandable code that other developers can read easily.
Quick Links
Legal Stuff