3 useful TypeScript and JavaScript shorthands to know
Md Riyazuddin
Verified
JavaScript and TypeScript share a number of useful shorthand alternatives for common code concepts. Shorthand code alternatives can help reduce lines of code.
In this article, we will review 3 common TypeScript and JavaScript shorthands.
1 - 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]
The following example demonstrates a traditional if…else
statement and its shorthand equivalent using the ternary operator:
// Longhand
const number = 80;
if (mark >= 50) {
return true;
} else {
return false;
}
// Shorthand
const number = 80;
return number >= 50 ? true : false;
2 - Short-circuit evaluation
Another way to replace an if…else
the 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 false.
The following example demonstrates how to use short-circuit evaluation:
// Longhand
let string = '';
let finalString;
if (string !== null && string !== undefined && string != '') {
finalString = 'default string';
} else {
finalString = string;
}
// Shorthand
let string = '';
let finalString = string || 'default string';
3 - 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
Comments
Leave a Comment