12 JavaScript short-hands that will help you code like an expert

Anurag MathewsAnurag Mathews
9 min read

The unnecessary code 📰

You often write helper codes that are not directly related to the core logic, those are some unnecessary lines of code in between your logic and directly affect your code readability.

Like writing a “for” loop with “If…else” for finding an element. For a simple task like this, writing the loop and condition is not very convenient. Imagine if you can shrink down this loop to a single line. That code will surely look like written by an expert. Clean and Readable!

That is what you will get in this article. I will show you 12 shorthand techniques that will help you write clean code, remove unnecessary lines and present your code like an expert 🧑‍🏫

12 Short-hands you should keep in your quiver 🏹

1️⃣ Shrink if…else statement to one line

if…else statement is what comes to our mind when we think of conditional checks. But in the case of conditional assignment, this, if…else block, is doing a simple assignment in 5-6 lines.

let x = 10;
let result;

//long-hand
if(x%2 === 0)
{
    result = "x is an even number"; 
} else {
    result = "x is an odd number";
}

Assignment operation should be done in one line, to achieve this we have an operator called

Ternary Operator. Use the ternary operator when you want to do the conditional assignment.

let x = 10;

//short-hand
let result = x % 2 === 0 ? "x is an even number" :  "x is an odd number";

2️⃣ Object values to Array

If you have an object and you have to create an array from object values, what will you do? Run a loop on the object?! Running a loop is fine, but it will take multiple lines for the assignment operation.

let person = {
    name: "Anurag",
    role: "Front-end Developer",
    country: "India"
}

//Long-hand
let personData = [];
for(let key in person) {
    personData.push(person[key]);
}

To do the same operation in a single line you can use Object.values() method.

let person = {
    name: "Anurag",
    role: "Front-end Developer",
    country: "India"
}

//short-hand
let personData = Object.values(person);

3️⃣ Find an element in the Array

You can find the element in an array using an index very easily, but when you don’t know exactly what is the index? or whether the element is present or not?

The first thing which might have come to your mind is a loop with if…else, which is not wrong.

const number= [5, 10, 15, 50, 97];
let found;

//Long-hand
for(let i = 0; i < numbers.length; i++) {
    if(number[i] === 15){
            found = number[i];
    }
}

console.log(found);

But, won’t it be great if we can do this in a single line too just like the above one? 🤔

The answer is yes, you can use the array method find() to write this same logic in a single line.

This method will return the first element which matches the specified condition and return undefined if the condition is not satisfied.

const number= [5, 10, 15, 50, 97];

//short-hand
const found = number.find(element => element === 15);

console.log(found);

4️⃣ Shorthand for if block

You don’t need the else block every time, like when you are showing a loading animation based on a variable value, you are not doing anything if the condition fails, so you can leave the else block.

//Long-hand
if(loading) {
    showLoading();
}

But again if we can remove all these curly braces { } and write this logic in a single line, that will look cleaner.

//short-hand
loading && showLoading();

This shorthand is really useful in React applications, you will find yourself using this in React a lot.

//short-hand
<div>{this.state.isLoading && <Loading />}</div>

5️⃣ De-structuring objects

You can store the object values to separate variables and use them instead of dot(.) notation. This is the more convenient approach to working with objects and is very common in React.

const person = {
    name: "Anurag",
    age: "25",
    country: "India",
    state: "M.P."
};

//long-hand
const name = person.name;
const age = person.age;
const location = {country: person.country,state: person.state};

The problem here is still you are using the dot(.) notation which you were trying to avoid in the first place and doing this simple task in multiple lines which are affecting the readability.

Let’s see how we can write this in single line and make it more readable.

const person = {
    name: "Anurag",
    age: "25",
    country: "India",
    state: "M.P."
};

//short-hand
const {name, age, ...location} = person;

6️⃣ Object Assignment

You have seen how you de-structure objects in a single line but what about assigning values to objects?

Object, need key and values when assignment. Usually, when creating objects dynamically you use stored values to create the object.

const name = "Anurag";
const age = 25;
const country = "India";
const state = "M.P.";

//long-hand
const personObj = {
    name : name,
    age : age,
    country : country,
    state : state
};

This seems unnecessary, doing a simple assignment would be more convenient if you can do it in a single line, right?

Let’s see how you can write that same assignment operation in a single line.

const name = "Anurag";
const age = 25;
const country = "India";
const state = "M.P.";

//short-hand
const personObj = {name,age,country,state};

JavaScript will use the variable name to create the key implicitly and assign the value to that key.

7️⃣ Check if the item is present in the Array

Finding whether an element is present in the array, will require writing a loop with if…else just to store a boolean result, followed by another if…else to perform the operation based on the obtained result.

const numbers = [1,6,15,2,11];
let result = false;

//long-hand
for(let i = 0 i < numbers.length; i++) {
    if(numbers[i] === 15){
        result = true;
        break;
    } 
}

if(result) {
    console.log("15 is present");
}else {
    console.log("15 is not present");
}

This simple task is taking more than 10 lines of code. What if I tell you, you can reduce this code to a single line, won’t that be incredible.

That will save you some time, writing one is way faster than writing 10 lines. An added benefit is improved code readability.

Let’s see how to write it in single line


const numbers = [1,6,15,2,11];

//short-hand
numbers.includes(15) ? console.log("15 is present") : console.log("15 is not present");

8️⃣ Remove Duplicates From an Array

Removing duplicate elements from an array is classic question which you will come across in online JavaScript tests.

It can be done in many ways, and most of them require you to write a loop

const numbers = [1,3,5,1,3,2,6];

//long-hand
let uniqueNums = [];
numbers.forEach((n) => {
    if (!uniqueNums .includes(n)) {
        uniqueNums.push(n);
    }
});

Many other ways will take the same approach of writing a loop and based on a condition filter and create new array with unique values.

Let me show, how to do this without loop and in a single line.

const numbers = [1,3,5,1,3,2,6];

//short-hand
const uniqueNums = [...new Set(numbers)];

9️⃣ Find the max and the min number in an array

Working with an array requires a loop 90% of the time. In most cases, it’s a combination of loop and condition inside it. Finding max and min numbers is no exception.

const numbers = [1,5,9,3,2,4];
let max = numbers[0];
let min = numbers[0];

//long-hand
forEach(num => {
    if(num > max) {
        max = num;    
    }else if(num < min) {
        min = num;
    }
});

You can write this logic using reduce() method to shrink it down, but let me show you a much easier way to write it, which will blow your mind 🤯

const numbers = [1,5,9,3,2,4];

//short-hand
let max = Math.max(...numbers);
let min = Math.min(...numbers);

1️⃣0️⃣ Deep cloning of multi-level object

You can easily copy a normal object with the spread operator (…), but the problem with the spread operator is it creates a shallow copy for multi-level objects. To create a deep copy you will have to write a recursive function and loop through each key-value pair. Such a pain! 😒

let person = {
    name : "Anurag",
    age: 25,
  location: {
        country: "India",
        state: "Madhya Pradesh"
    }
};

//long-hand
const makeClone = (obj) => { 
  let newObject = {}; 
  Object.keys(obj).map(key => { 
    if(typeof obj[key] === 'object'){ 
      newObject[key] = makeClone(obj[key]); 
    } else { 
      newObject[key] = obj[key]; 
    } 
  }); 
 return newObject; 
} 

const deepClone = makeClone(person);

That much code just to copy an object; totally unnecessary. Simple tasks should be done simply. Imagine if you tell someone you can reduce this complex code to a single line. Trust me, it will blow their mind.

let person = {
    name : "Anurag",
    age: 25,
  location: {
        country: "India",
        state: "Madhya Pradesh"
    }
};

//short-hand
cosnt deepClone = JSON.parse(JSON.stringify(person));

1️⃣1️⃣ Flatten the nested Array

Working with the nested array is difficult, you access values through the index and there is no way you know which index has a nested array. The best thing is, to flatten the array. This is a very common question you might come across in coding interviews. But how to flatten the array?

There are multiple approaches to this problem, you can use reduce() and concat() methods to get a flattened array.

const numbers = [1, [2, 3, [4, [5]], 6], 7];

//long-hand
function flatten(arr) {
    return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []);
};

const flattened = flatten(numbers);

This is not at all a bad approach, but you can make it even better, because why not?!

However, I suggest you remember both, this can be really handy for your interviews.

const numbers = [1, [2, 3, [4, [5]], 6], 7];

//short-hand
const flattened = numbers.flat(Infinity);

1️⃣2️⃣ Assigning a default value to a variable

Assigning a default value is a conditional operation, you have seen Ternary Operator can be used to do these simple operations in a single line, in a cleaner way.

//long-hand
let name = assignedName ? assignedName : "Not assigned";

You can say, this approach is fine Anurag, it’s clean and readable.

You are right! But in this case, you are not looking for a condition, it’s simply either this or that. So, why to use a conditional operator for this, it’s unnecessary.

Let me show you, how you can do it better. This is known as Nullish Coalescing (??)

//short-hand
let name = assignedName ?? "Not assigned";

You can also use Short-Circuit Evaluation (||)

//short-hand
let name = assignedName || "Not assigned";

Conclusion

Coding is a combination of all these simple logic. These short-hands don’t seem to make any impact when you see them in an isolation, but they will definitely be a game-changer when you use them in your code.

Writing clean, readable code will make a big difference, it's easier to debug, it's easier for other developers to understand, and when you remove all the unnecessary lines you can actually see what you have written.

Keeping code clean and readable has many advantages and using these short-hands makes it convenient to write clean, readable code and that will make you stand out from other developers.

If you think this article was helpful, I would really appreciate it if you can drop a 👍

Comment which short-hand you find most interesting 📝

If you want to connect with me 👇
Do follow me on Twitter @anuragmathews08

Happy coding ✌️

References

21
Subscribe to my newsletter

Read articles from Anurag Mathews directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anurag Mathews
Anurag Mathews

I am a Front-end developer who loves working with JavaScript & Reactjs. Here I am to help you by sharing what I know & learned in more than 3 years of my journey. I will make sure you avoid the mistakes I made & you have a smoother journey.