JavaScript and TypeScript are highly popular programming languages in the field of web development. They both have extensive feature sets and many syntax shortcuts which significantly contribute to improving coding efficiency.

Learn how to tighten up your code and make the most of these languages with some useful shortcuts.

1. Ternary Operator

The ternary operator offers a concise and efficient syntax for expressing conditional statements. It has three parts: a condition, an expression to run if the condition evaluates to true, and an expression to run if it’s false.

This operator proves particularly useful when making decisions based on conditions and assigning different values accordingly.

Consider the following example:

        const age = 20;
const ageType = age >= 18 ? "Adult" : "Child";
console.log(ageType); // Output: "Adult"

This example uses the ternary operator to check if the variable age is greater than or equal to 18. If it is, the code assigns the value Adult to the variable ageType, otherwise it assigns the value "Child".

2. Template Literals

Template literals offer a powerful and efficient way of formatting JavaScript strings and incorporating variables or expressions within them. Unlike traditional string concatenation using single or double quotes, template literals use backticks (`).

This unique syntax provides several advantages when working with strings. Consider the following example that demonstrates the usage of template literals:

        const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: "Hello, Alice!"

The example includes the name variable in the template literal using ${}. This lets you easily construct dynamic strings.

3. Nullish Coalescing Operator

The nullish coalescing operator (??) provides a convenient way to assign default values when a variable is either null or undefined. It returns the right-hand side operand if the left-hand side operand is null or undefined.

Consider the following example:

        const username = null;
const displayName = username ?? "Guest";
console.log(displayName); // Output: "Guest"

In this example, since the variable username is null, the nullish coalescing operator assigns the default value Guest to the variable displayName.

4. Short-Circuit Evaluation

Short-circuit evaluation allows you to write concise conditional expressions using logical operators such as && and ||. It takes advantage of the fact that a logical operator will stop evaluating expressions as soon as it can determine the result.

Consider the following example:

        const name = "John";
const greeting = name && `Hello, ${name}`;
console.log(greeting); // Output: "Hello, John"

This example will only evaluate the expression `Hello, ${name}` if the variable name has a truthy value. Otherwise, it short-circuits and assigns the value of name itself to the variable greeting.

5. Object Property Assignment Shorthand

When creating objects, you have the option to use a shorthand notation that assigns variables as properties with the same name.

This shorthand notation eliminates the need to redundantly state both the property name and the variable name, resulting in cleaner and more concise code.

Consider the following example:

        const firstName = "John";
const lastName = "Doe";
const person = { firstName, lastName };
console.log(person); // Output: { firstName: "John", lastName: "Doe" }

This example assigns the properties firstName and lastName using shorthand notation.

6. Optional Chaining

Optional chaining (?.) allows you to access nested properties of an object without worrying about intermediate null or undefined values. If a property in the chain is null or undefined, the expression short-circuits and returns undefined.

Consider the following example:

        const user = { name: "Alice", address: { city: "New York", country: "USA" }};
const country = user.address?.country;
console.log(country); // Output: "USA"

In the example above, the optional chaining operator ensures that the code doesn't throw an error if the address property or the country property is missing.

7. Object Destructuring

Object destructuring is a powerful feature in JavaScript and TypeScript that allows you to extract properties from objects and assign them to variables using a concise syntax.

This approach simplifies the process of accessing and manipulating object properties. Let's take a closer look at how object destructuring works with an example:

        const user = { name: "John", age: 30 };
const { name, age } = user;
console.log(name, age); // Output: "John" 30

This example extracts the variables name and age from the user object via object destructuring.

8. Spread Operator

The spread operator (...) enables you to expand elements of an iterable, like an array or object, into individual elements. It is useful for combining arrays or creating shallow copies of them.

Consider the following example:

        const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers); // Output: [1, 2, 3, 4, 5]

In the example above, the spread operator expands the numbers array into individual elements, which are then combined with 4 and 5 to create a new array, newNumbers.

9. Object Loop Shorthand

When iterating over objects, you can use the for...in loop in combination with object destructuring to conveniently iterate over object properties.

Consider this example:

        const user = { name: "John", age: 30 };

for (const [key, value] of Object.entries(user)) {
    console.log(`${key}: ${value}`);
}

// Output:
// name: John
// age: 30

In the example above, Object.entries(user) returns an array of key-value pairs, which each iteration then destructures into the variables key and value.

10. Array.indexOf Shorthand Using the Bitwise Operator

You can replace calls to the Array.indexOf method with a shorthand using the bitwise operator ~ to check if an element exists in an array. The shorthand returns the index of the element if found or -1 if not found.

Consider the following example:

        const numbers = [1, 2, 3];
const index = ~numbers.indexOf(2);
console.log(index); // Output: -2

In the example above, ~numbers.indexOf(2) returns -2 because 2 is at index 1, and the bitwise operator negates the index.

11. Casting Values to Boolean With !!

To explicitly convert a value to a boolean, you can use the double negation operator (!!). It effectively converts a truthy value to true and a falsy value to false.

Consider the following example:

        const value1 = "Hello";
const value2 = "";
console.log(!!value1); // Output: true
console.log(!!value2); // Output: false

In the example above, !!value1 returns true because the string Hello is truthy, while !!value2 returns false because the empty string is falsy.

Unlocking Code Efficiency and Readability

By utilizing these shorthands in JavaScript and TypeScript, you can enhance your coding efficiency and produce more concise and readable code. Whether it's using the ternary operator, short-circuit evaluation, or leveraging the power of template literals, these shorthands provide valuable tools for efficient coding.

Additionally, the object property assignment shorthand, optional chaining, and object destructuring simplify working with objects, while the spread operator and array shorthands enable efficient array manipulation. Mastering these shorthands will make you a more productive and effective JavaScript and TypeScript developer.