Some of the best shortcuts when writing Javascript and Typescript
Tags: javascript, webdev, typescript, node
Published: 2020-09-04 07:51:24

Everyone knows that Javascript and Typescript have several weird and hidden features that allow you to shorten the amount of code you write. To preface this article, I’d like to impose upon you an important tidbit of information, **short and efficient code doesn’t always equal good code.** As always, you should be prioritizing readability over implementing a bunch of fancy features.

That being said, these features can help you save tons of space and used properly are easily understandable to anyone else who’s reading your code. Let’s go over some of these shorthand features so that you can use and understand them in your code.

# 1. The Ternary Operator

This is probably the most well known shorthand Javascript function, the shortened “if else” statement. By using this operator, you can remove a lot of the `if else` boilerplate and turn four lines into one!

```js
let v = true;

// Traditional approach
if (v) {
	console.log('True');
} else {
	console.log('False');
}

// Ternary Operator
v ? console.log('True') : console.log('False');
```

The structure is as follows: `<conditional expression> ? <true case> : <false case?`. Pretty simple, right? This is a great way to do one line if else operations and is especially useful when combined with other shorthand operators.

# 2. Typescript’s Constructor Shorthand
This one is particularly for Typescript (Sorry vanilla JS users), but is a great feature when building classes.

Normally in a class you have to list all your class variables then reassign them in your constructor, which takes tons of lines of code. But if your class is relatively simple (you’re just assigning parameters to private variables), Typescript has a great way to cut the amount of code you write.

```ts
// Normal way
class Location {
	private _latitude: string;
	private _longitude: string;

	constructor(latitude: string, longitude: string) {
		this._latitude = latitude;
		this._longitude = longitude;
	}
}

// Shorthand in TypeScript
class Location {
	constructor(
		private _latitude: string,
		private _longitude: string
	) {}
}
```

On larger classes with tons of properties, this can be a real life saver!

# 3. Nullish Operator
Often misunderstood, the nullish operator lets you easily evaluate an expression and check if it’s null, and return a default value if it is null.

```ts
function nullish(value1, value2) {
	// If value1 is null returns 'default'
	let v1 = value1 ?? 'default';
	return v1 + value2;
}

myFn("this has no") //returns "this has no default"
myFn("this has no", 0) //returns "this has no 0"
```

Actually, technically it checks for `null` or `undefined`, but the name is close enough. This is a great way to check if values exist or not.

# 4. Object Property Assignment
ES6 simplified the process of assigning values to objects. If values are assigned to variables named exactly as the object’s properties, you won’t have to repeat the name!

```ts
let name: string = "Caelin";
let age: number = 18;

interface User {
	name: string;
	age: number;
}

// Old way (manual assignment)
let user1: User = {
	name: name,
	age: age,
}

// New way!
let user2: User = {
	name,
	age,
}

```

As shown above, the new way is considerably simpler and DRYer than the old way!

# 5. Arrow/Lambda Functions

If you’ve seen a lot of these operators:  `=>` thrown around everywhere, they’re arrow functions. These allow you to save a `return` statement since any lamda function will have a default return.

You’ll seen them often used in array operators as such:

```js
let arr = [1, 2, 3, 4, 5];

// Long way
arr.map(function (n) {
	return n*2;
})

// Short way
arr.map(n => n*2);
```

As you can see, it makes the code considerably more readable and shorter.

# 6.. Default Parameter Values
ES6 now allows you to specify default parameter values on functions! Before, you’d have to rely on OR’s lazy evaluation, which worked but was a suboptimal solution. 

```js
// Assigns 'c' a default value
function defaultParams(a, b, c="c") {
	return a + b + c;
}
```
 
Fun tip, if you want to make a required parameter, do the following:
```js
const requiredParam = _ => throw new Error('Required Parameter!');

// Create a default parameter d
function defaultParamRequired(a, b, c="c", d=requiredParam()) {
	// Logic
}
```

Now, if this function is ran without passing a default parameter d in, it’ll throw an error! Pretty cool trick right?

# 7. Destructuring and Spread Operators

I literally wrote a whole article on [spread operators](https://cometcode.io/posts/javascript-spread-operator/), but spread and destructing operations are great ways to take advantage of object and arrays!

## Destructuring
It’s quite common to want to access an objets parameters individually (to modify or read them) without accessing the original object. Normally, this would require a line for each object parameter, which can get quite long on larger objects. Object destructuring allows us to cut that into one line!

```js
const user = {
	name: 'Caelin',
	age: 18,
}

// Normal method
const name = user.name;
const age = user.age;

// Destructuring method
const {name, age} = user;
```

This syntax is great for object parameters and import statements to reduce the amount of lines when dealing with complex objects.

## Spreading

Spread operators make it easier to combine objects and arrays by expanding them.

```js

const arr1 = [1,2,3,4]
const arr2 = [5,6,7]

const finalArr = [...arr1, ...arr2] // [1,2,3,4,5,6,7]

const partialObj1 = {
  name: "fernando"
}
const partialObj2 = {
  age:37
}

const fullObj = { ...partialObj1, ...partialObj2 } // {name: "fernando", age: 37} 
```

# Conclusion

These are just a few of the many Javascript and Typescript shortcuts that can save you time and make your code cleaner. Remember, this is not simply about making code more efficient or reducing lines, it’s about making code that’s cleaner and easier to read for the next developer.

Did I miss something? Be sure to comment it down below!

# Keep in Touch
There's a lot of content out there, I appreciate you reading mine. I'm a young entrepreneur and I write about software development and my experience running companies. You can signup for my newsletter [here](https://newsletter.cometcode.io)

Feel free to reach out and connect with me on [Linkedin](https://www.linkedin.com/in/caelinsutch) or [Twitter](https://twitter.com/caelin_sutch).