Top Javascript and Typescript Short-hand You must know
Tags: node, javascript, programming, tutorial
Published: 2022-06-07 16:45:56

## 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.

<hr>

## 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:

1. `condition`
2. Truthy value followed by a colon
3. Falsy value



```javascript
// 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.

```javascript
// 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.

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

```

<hr>


## 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**.

```javascript
// syntax
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)

```

```javascript
// 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`.

```javascript
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
```

<hr>


## Nullish Coalescing Operator:

**Nullish Coalescing Operator** is another logical operator. It is written as **two question mark symbol** `??`. 

```javascript
// syntax
leftExpression ?? rightExpression
```

It returns the `rightExpression` if `leftExpression` is null or undefined otherwise, it returns `leftExpression`.

```javascript
// 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.

<hr>



## 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.

```javascript
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.


<hr>


## 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.

```javascript
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.

```javascript
class Person {
   constructor (public name: string,public age: string) {}
}
```

Note: This short-hand is working with **Typescript** only.


<hr>


## 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**.

```javascript
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
}

```

<hr>


## 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.

```javascript
// syntax

{property1: variable1, property2: variable2} = object
```

Below example is an example of the object destructuring:

```javascript
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:

1. Assign values to existing variables.
2. Assign values to new variables.
3. Assign to a variable with default values.

```javascript
// Assign values to existing variables

let person = {
    firstName: 'John',
    lastName: 'Doe'
};

let {firstName, lastName} = person;
```

```javascript
// 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:

```javascript
// 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

```

<hr>


## 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`).

```javascript
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:

1. Copy Array Using Spread Operator.
2. Clone Array Using Spread Operator.
3. Spread Operator with Object.


### Copy Array Using Spread Operator:

```javascript
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4, 5];

console.log(arr2) // [1, 2, 3, 4, 5]
```

### Clone Array Using Spread Operator:

```javascript
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:

```javascript
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 :

* [Email](mailto:imvaibhavsharma@outlook.com)
* [Twitter](https://twitter.com/iaamvaibhav)
* [My Blog](https://blog.iamvaibhav.com/)