Save some time use Shorthand

Ahmed A.
3 min readNov 6, 2020

--

While writing lines and lines of code in JavaScript it is helpful and make your code look cleaner by using some shorthand JavaScript techniques. In this article I will show you a few.

Declaring Variable

We will start with declaring variables because usually it is one of the first things you will do in your program. You can save plenty of space and time by declaring your variables on one line.

Check if Something is true

Although the below example is not exactly equal, it still works and is a common shortcut

For Looping

Also with looping if you want to get the index or the key in the array you can write…

for(let index in colors) or for (let key in colors)

Template Literals

Instead of using the (+) and concatenate strings we can use ` ${variable}` those are backtiks not quotes.

Destructuring

while using a frame work like React JS, you will most likely use arrays or data in the form of object literals to pass date between APIs and components. You will need to unpack it.

Making Mandatory Parameter

JavaScript will set function parameters as undefined when not passed a value. If you what to force a parameter to be assigned a easy short hand trick is below.

Ternary Operator

Using a ternary operator can save you lots of line of code you can put multiple lines of code into one line that is easier to read.

Arrow Function

Another way to write a function is with a arrow function which is also a little easier to read.

Object Property Assignment

When a variable name and a object key’s name is the same then we only need to mention the variable name instead of both the key and the value. JavaScript will take care of the rest for you like magic.

Merge Arrays

This shortcut takes advantage of using a spread operator.

Conclusion

These listed shortcuts are only a few shortcuts of many, they can be used to cut down on time and length of your code. They can also help make your code more readable and easier to follow, as long as you know how to use these they will make your coding journey better. Take some time to research some other there are plenty out there.

--

--