Introduction
As a Javascript and Typescript Developer, you will review the code of other senior developers. They will use some other syntax that we are not familiar with. But today I will tell you Top short-hand syntax of Javascript and Typescript, which will help you to understand the other developer's code and fasten your developer speed also.
Ternary Operator :
The Ternary Operator is also known as Conditional Operator. This operator is used as shorthand for if...else
. if you want to run else if
block also, you need to perform a ternary chaining operation. This conditional operator is the only operator that will take 3 operands:
condition
- Truthy value followed by a colon
- Falsy value
// syntax
condition ? truthyExpression : falsyExpression
The below example illustrates how we will use the first if...else
block and after that same code block with the ternary
operator.
// if...else
var age = 20;
if(age >= 18) {
πΊ
} else {
π§
}
// short-hand
var age = 20;
var beverage = (age >= 18) ? πΊ :π§
console.log(beverage); // πΊ
If you want to perform the else if
operation, then you need to chaining because it has a right-associative property.
// ternary operation chaining
condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
Optional chaining:
Optional Chaining operator ?.
enables you to not check the nested object property validation each time. ?.
is the safest way to access the nested object property in both conditions is nested property exists or not. This operator solves the non-existing problem.
// syntax
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
// Normal Developer
let nestedProperty = object.name && object.name.firstName;
// π Developer
let nestedProperty = object.name?.firstName;
In the below example, we are trying to access the homeAddress
property of an empty object person
. If we will try to access without optional chaining then we will get Reference Error (TypeError: Cannot read property 'homeAddress' of undefined
). But if we will try to access the same property with the use of optional chaining then we are not getting error, but in the place we are getting undefined
.
let person = {};
console.log(person.address.homeAddress) // TypeError: Cannot read property 'homeAddress' of undefined
// This is known as a non-existing problem.
/* Optional Chaining */
let person = {};
console.log(person?.address?.homeAddress) // undefined
Nullish Coalescing Operator:
Nullish Coalescing Operator is another logical operator. It is written as two question mark symbol ??
.
// syntax
leftExpression ?? rightExpression
It returns the rightExpression
if leftExpression
is null or undefined otherwise, it returns leftExpression
.
// long code
const str = null;
let value;
if(str !== null || str !== undefined) {
value = str;
} else {
value = 'some-value';
}
// short-hand
const value = null ?? 'some-value';
console.log(value); // some-value
const value1 = ' ' ?? 'some-value';
console.log(value1); // ' '
The nullish coalescing operator has the fifth-lowest operator precedence, directly lower than || and directly higher than the conditional (ternary) operator.
Template Literals:
Template Literals is the EcmaScript 6 feature. By the use of Template Literal we can wrap the multiple variables with string without using of +
operand.
// syntax
``
We can use ${}
to wrap the variable with a string. This is also known as string interpolation.
const name = "Vaibhav";
// long code
console.log('Good morning ' + name);
// short-hand
console.log(`Good morning ${name}`)
We can use template literals for multi-line string, string interpolation, and tagged templates.
Typescript Constructor Shorthand:
You all know about class constructors in javascript and typescript. class declaration is one way to create classes. To declare the classes, we will use the class
keyword. With the use of constructor
, we will assign the values to class properties.
class Person {
public this.name;
public this.age;
constructor(name, age) {
this.name = name;
this.age = age;
}
}
In Typescript, when we are using the constructor. it automatically creates and sets the class properties.
class Person {
constructor (public name: string,public age: string) {}
}
Note: This short-hand is working with Typescript only.
Object property assignment shorthand:
Object property assignment is Javascript and Typescript also has a short-hand. If you need to assign a variable value to an object property, you don't need to specify the variable name, if the object's property name and the variable name is the same.
const name = "Vaibhav";
const age = 26;
const greet = "Good Morning"
// long-code
const me = {
name : name,
age: age,
greeting: greet
}
// short-code
const me = {
name,
age,
greeting: greet
}
Object Destructuring:
In Javascript, by the use of destructuring we will extract the data from an object, array, and map and set it to new variables with the same name. Destructuring is another ES6 feature. Destructuring also works with complex functions that have a lot of parameters and default values.
// syntax
{property1: variable1, property2: variable2} = object
Below example is an example of the object destructuring:
let person = {
firstName: 'John',
lastName: 'Doe'
};
// long-code
let firstName = person.firstName;
let lastName = person.lastName;
// short-code
let {firstName, lastName} = person;
There are three use-cases examples of object destructuring:
- Assign values to existing variables.
- Assign values to new variables.
- Assign to a variable with default values.
// Assign values to existing variables
let person = {
firstName: 'John',
lastName: 'Doe'
};
let {firstName, lastName} = person;
// Assign values to new variables
let person = {
firstName: 'John',
lastName: 'Doe'
};
let {firstName: fname, lastName: lname} = person;
// fname = 'John', lname = 'Doe'
We can also assign default values to variables whose keys may not exist in the object. If those values are not present it will give undefined values that's why we are using default values for preventing any issue due to undefined values. The code below demonstrates this:
// Assign to a variable with default values
let person = {
firstName: 'John',
lastName: 'Doe'
};
let {firstName= 'Vaibhav', lastName= 'Sharma', age= 27} = person;
// firstName = 'John', lastName = 'Doe', age = 27
Spread operator:
Spread syntax aka spread operator is the coming with ES6. Spread operator (...)
is used to expand or spread an iterable (i.e. array
or string
).
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const numbersCombined = [...arr1, ...arr2];
// 1,2,3,4,5,6
There are several use-cases where we can use spread operator like:
- Copy Array Using Spread Operator.
- Clone Array Using Spread Operator.
- Spread Operator with Object.
Copy Array Using Spread Operator:
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4, 5];
console.log(arr2) // [1, 2, 3, 4, 5]
Clone Array Using Spread Operator:
let arr1 = [ 1, 2, 3];
// copy using spread syntax
let arr2 = [...arr1];
The above example creates two different references, so removing and adding elements to one array will not affect the other.
Spread Operator with Object:
const obj1 = { a : 'x', b : 'y' };
const obj2 = { c : 'z' };
// add obj1 and obj2 to obj3
const obj3 = {...obj1, ...obj2};
console.log(obj3); // {a: 'x', b: 'y', c: 'z'}
Conclusion:
These are very few short-hand codes. I was worried about the length of the article that's why I have added only 8 short-hand codes. If guys you want the next article of this series please let me know. I will work on that for sure. If you want to connect with me, please free to connect with me :
Top comments (3)
These are so useful thanks for the notes.
Your "Template Literal" is a poor example - the 'long code' and 'shorthand' are exactly the same length... and the long code will actually be shorter if you remove the unnecessary spaces
Hi Jon
Thanks for reading my article. In this article long code and short code is not compare by length only its compare by complexity also. When we were wrapping the variable with string earlier, sometime we were missing to add '+' and then we were getting error.
But with Template literals, we will not get any error. That is the mean by long code and short code.
Thanks again @jonrandy