Enhance Your Coding with JavaScript and TypeScript Shorthand Techniques

LogRocket Dashboard Free Trial Banner

Optimizing your workflow is one of the key steps to becoming a proficient developer, and a great way to do that is by learning and implementing shorthand alternatives in your code. Two languages that offer many opportunities for shorthand coding are JavaScript and TypeScript. This guide will walk you through several shorthand alternatives that can make your code cleaner, more scalable, and easier to read.

Table of Contents

Ternary Operator

A ternary operator is a shortcut for an if...else statement, and is made up of three parts: a condition, a result for true, and a result for false. Here’s an example of how it can simplify your code:

// Longhand
const mark = 80;
if (mark >= 65) {
  return 'Pass';
} else {
  return 'Fail';
}

// Shorthand
const mark = 80;
return mark >= 65 ? 'Pass' : 'Fail';

Short-circuit Evaluation

This is a less-known yet handy feature that uses the OR (||) operator. It allows you to run an operation not when the first operand is true, but when the first operand is false.

// Longhand
let str = '';
let finalStr = str || 'default string';

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

Nullish Coalescing Operator

The nullish coalescing operator checks whether a provided variable is null or undefined and returns a provided default value if it is null or undefined. It’s a shorter and more intuitive way to default-assign your variables.

// Longhand
let num = null;
if (num !== null && num !== undefined) {
  actualNum = num;
} else {
  actualNum = 0;
}

// Shorthand
let num = null;
let actualNum = num ?? 0;

Template Literals

Template literals, introduced with the ES6 syntax, allow for easier string manipulation. They are a new way to create strings and allow embedded expressions, multiline strings, and string formatting.

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

// Shorthand
const name = 'Iby';
const hobby = 'to read';
const fullStr = `${name} loves ${hobby}`;

Object Property Assignment Shorthand

In JavaScript and TypeScript, you can assign a property to an object in shorthand. This simply involves mentioning the variable in the object literal.

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

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

Optional Chaining

The optional chaining operator permits reading the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

// Longhand
const obj = {
  x: {
    y: 1,
    z: 2
  },
  others: ['test', 'tested']
};
if (obj.hasOwnProperty('others') && obj.others.length >= 2) {
  console.log('2nd value in others: ', obj.others[1]);
}

// Shorthand
const obj = {
  x: {
    y: 1,
    z: 2
  },
  others: ['test', 'tested']
};
console.log('2nd value in others: ', obj.others?.[1]);

Object Destructuring

Object destructuring allows you to create a new variable by extracting some properties from an object and can greatly simplify your code.

// Longhand
const obj = {
  x: {
    y: 1,
    z: 2
  },
  other: 'test string',
};
console.log('Value of z in x: ', obj.x.z);
console.log('Value of other: ', obj.other);

// Shorthand
const obj = {
  x: {
    y: 1,
    z: 2
  },
  other: 'test string',
};
const { x, other } = obj;
const { z } = x;
console.log('Value of z in x: ', z);
console.log('Value of other: ', other);

Spread Operator

The spread operator allows an iterable to be expanded in places where zero or more arguments or elements are expected. In simpler terms, it’s a quick, easy way to copy all properties from one object to another or to combine two different arrays.

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

Continue reading for more detailed explanation and examples of each shorthand…

Tags: #JavaScript #TypeScript #ProgrammingShorthands #CodingTips
Reference Link