20 Useful JavaScript Tips &Tricks For Writing Short and Clean Code

Featured on daily.dev
20 Useful JavaScript Tips &Tricks For Writing Short and Clean Code

Hey guys👋 JavaScript is no doubt one of the coolest and currently the trendiest language in the world that is gaining more and more popularity every day. Therefore, I thought, why not write about it, so here I am! In this article, I have compiled a list of tricks that will make you a better developer while helping you write short, concise, and clean code.

All of these tricks accomplish tasks that most developers need to perform on a daily basis. Depending on your experience you might already know some of these tricks, while some others could possibly blow your mind (that's what I'm hoping for!).

So without any further ado, let's get started!

1. Shortening "For Loop"

A normal "for loop" is written like this:

const fruits = ["Apple", "Mango", "Peach"];

for (let i = 0; i < fruits.length; i++) {
  const fruit = fruits[i];
  console.log(fruit);
}

But we can actually shorten it!

const fruits = ["Apple", "Mango", "Peach"];

for (let fruit of fruits) console.log(fruit);

2. Convert to string

Usually, in order to convert a number to a string, we write this code:

let num = 5
let newNum = num.toString();

But we can use the concatenation operator + followed by an empty set of quotation marks " " to quickly convert a number to a string.

const val = 3 + "";

console.log(val); // Output: "3"

console.log(typeof val); // Output: "string"

3. Convert to number

Usually, in order to convert a string to a number, we write this code:

let num = "6"
let stringNumber = Number(num);

But by the help of the addition operator +, we can code much faster.

let int = "16";
int = +int;

console.log(int); // Output: 16
console.log(typeof int); //Output: "number"

4. Convert Boolean to number

The method mentioned in point # 03 can also be used to convert booleans to numbers, as below:

console.log(+true);  // Return: 1
console.log(+false); // Return: 0

5. Convert to Boolean

We can easily convert a value to Boolean using !!

console.log(!!""); // Output: false
console.log(!!" "); // Output: true
console.log(!!0); // Output: false
console.log(!!1); // Output: true

6. .from()

The array method, .map() also has a substitute that can be used, which is .from():

let students = [
    { name: ‘Rahim’, age: 7 },
    { name: ‘Mac’, age: 9 },
    { name: ‘Bruno’, age: 7 },
    { name: ‘Jucas’, age: 9 },
    { name: ‘Sana’, age: 8 },
    { name: ‘Sara’, age: 7 },
]

let studentsNames = Array.from(students, ({name}) => name);
console.log(studentsNames); // returns [“Rahim”, “Mac”, “Bruno”, “Jucas”, “Sana’”,“Sara”]

7. Filtering Unique Values

The Set object type was introduced in ES6. Along with ..., the ‘spread’ operator, it can be used to create a new array with only unique values.

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];

console.log(uniqueArray); // Output: [1, 2, 3, 5]

Before ES6 was introduced, the process of isolating unique values would involve a lot more code than just that!

This trick works for arrays containing primitive types:

  • undefined

  • null

  • boolean

  • string

  • number

Note: If your array contains objects, functions, or additional arrays, this method won't work!

8. Avoiding if statements using AND

To understand how to do it, let's take a look at an example where we have a boolean value and a function;

let isPrime = true;
const startProgramming = () => {
    console.log('Started Programming!');
}

This is too much code for checking the boolean condition and invoking the function,

if (isPrime) {
    startProgramming();
}

How about we ditch the if statement altogether by using the AND(&&) operator? Yes, avoiding the if statements altogether.

isPrime && startProgramming();

Cool trick, isn't it?

9. Object destructuring

I know that it's a mouthful, "object destructuring". I was quite skeptical about it at first and thought it would be a tough nut to crack. But once you understand this concept, it’s probably going to be something that you will use every single day.

So that brings us to the question: what exactly is destructuring?

Destructuring is a JavaScript expression that helps you to extract data from arrays, objects, maps and sets into their own variable. It helps you to extract properties from an object or even items from an array. It can extract multiple items or properties at a time.

To understand it, let’s take a look at the following example where we have a user object. If you want to store the user’s name in another variable, then you have to assign it to a variable on a new line. And if you want to store the age as well in a variable, you’d have to do the same again.

const user = {
    name: 'Mike',
    age: 25,
    gender: 'M',
    member: false
}

const name = user.name
const gender = user.gender

By using destructuring, you can directly get the variables for the object’s properties through the following syntax:

const { name, age, gender, member } = user;

console.log(name)   // Mike
console.log(age)    // 25
console.log(gender) // M
console.log(member) // false

10. Swapping variables

Swapping has become super easy using the concept of destructuring we learnt just now.

let name = 'Mike';
let fruit = 'Apple';

[fruit, name] = [name, fruit];
console.log(name, fruit);

11. isInteger

There is a short method to know if a value is an integer. The Number API of JavaScript provides such a method called, isInteger() to do this task. It is a useful method that you should be aware of!

let mynum = 253;
let mynumStr = "253";

console.log(`${mynum} is a number?`, Number.isInteger(mynum));
console.log(`${mynumStr} is a number?`, Number.isInteger(mynumStr));

12. Convert Hexadecimal to integer

JavaScript can convert any Hexadecimal to a Number through this magic trick.

console.log(0xB) // 11
console.log(0xD) // 13
console.log(0xff) // 255

Sometimes, you just don't want to copy/paste all links from a document manually. Doing so is quite annoying. Well no worries, JavaScript to the rescue! You can easily get an array of all links in the document through the following line of code:

var allLinks = document.links;

14. Comma operator

We all actually ignore the good old comma, don't we? Well, here's a little info on this guy that you should know. It evaluates each of its operands (from left to right) and then returns the value of the last operand.

let x = 1;

x = (x++, x);

console.log(x); // expected output: 2

x = (2, 3);

console.log(x); // expected output: 3

15. Usage of “e”

There are times when you have to type out a lot of zeroes which can be daunting, after all we just tend to forget how many zeroes did we actually type. In this case, use “e” for excessive zeroes as shown in the example below:

console.log( 1e5 ); // 100000
console.log( 3e1); // 30

16. How to clone an Object

Cloning an object can be done easily through the lines of code given below:

// for deep cloning an object
var newObj = JSON.parse(JSON.stringify(obj));

// for shallow cloning an object
var newObj = Object.assign({}, obj);

17. Division + round down

By this method, you can divide any number in half, round down.

console.log( 28 >> 1 ); // 14
console.log( 29 >> 1 ); // 14
console.log( 4 >> 1); // 2
console.log( 5 >> 1); // 2

18. Use Semicolons

Using semi-colons for line termination is a good practice. For all those C++ folks out there, it isn't much of a difference, right? Though you won’t be warned if you forget it as in most cases it will be inserted by the JavaScript parser.

19. Use a switch/case statement instead of a series of if/else

Usage of switch/case is faster when there are more than 2 cases. It is a more elegant and better-organized code. Moreover, you can also use switch/cases with numeric ranges by help of the following trick:

function getGroup(age) {  
    var group = "";  
    switch (true) {  
        case isNaN(age):  
            group = "not an age";  
            break;  
        case (age >= 40):  
            group = "Old";  
            break;  
        case (age <= 18):  
            group = "Adult";  
            break;  
        default:  
            group = "Young";  
            break;  
    };  
    return group;  
}  
getGroup(16);  // will return "Adult"

If we had used if/else statement to write this code, it would have been so messy and the code would not be readable!

20. Getting a random number in a specific range

This code snippet will be pretty useful when you have to generate fake data for testing purposes, such as a salary between min and max.

var x = Math.floor(Math.random() * (max - min + 1)) + min;

Conclusion

I hope that you found these tips as useful as I did when I first discovered them. Do you know of any cool and useful JavaScript tricks? I’d love to read them in the comments!