JavaScript Tips and Best Practices
Tags: javascript, typescript, computerscience, beginners
Published: 2021-07-04 09:30:09

In this article, I’ll share 10 of the JavaScript tips, tricks, and best practices that I follow and found useful.

## 1. Use Numeric Separators

This is one of the most used operators when I have to deal with large numbers. When using a separator (with just an \_) in number it looks better than an unseparated number.

For example:

```javascript
let number = 98234567
```

to ⬇

```javascript
let number = 98_234_567
```

And it works for any other numeric base as well:

```javascript
const binary = 0b1000_0101;
const hex = 0x12_34_56_78;
```

**Few caveats** :

- Can not be used after leading 0. 
```javascript
let num= 0_12
```

- Not allowed at the end of numeric literals. 
```javascript
let num= 500_
```

## 2. Always Use Semicolons

The use of semi-colons for line termination is a good practice. You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser but relying on Automatic Semicolon Insertion(ASI) is not encouraged.

This is even included in [Google’s](https://google.github.io/styleguide/jsguide.html#formatting-semicolons-are-required), [Airbnb’s](https://github.com/airbnb/javascript#semicolons), and [jQuery’s](https://contribute.jquery.org/style-guide/js/#semicolons) Javascript style guides.

To know about what could happen if we rely too much on ASI, checkout the [4th issue of my newsletter](https://newsletter.apoorvtyagi.tech/issues/but-it-works-on-my-machine-407281) I shared some months back. In the last section, I have explained it with an example.

## 3. Don’t forget "var"

When you assign a variable’s value for the first time, always make sure you're not doing it to an undeclared variable.

Assignment to an undeclared variable automatically results in a global variable being created. **Avoid global variables** ❌

Global variables are easily overwritten by other scripts. For example, if two separate parts of an application define global variables with the same name but with different purposes, it can result in unpredicted errors and it will be a horrible experience to debug such a problem.

Generally, you should try to scope your code so that you need as little as possible in the global scope. The more global variables you use in your script, the less is the chance that you can use it alongside another script.

Normally variables in a function should be local so that they go away when you exit the function.

> "By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries." - Douglas Crockford

## 4. Delete vs Splice

Use splice instead of using delete to remove an item from an array. Using delete will remove the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined.

### Delete

```javascript
> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined
```

> Note that it is not in fact set to the value undefined, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty when logging the array.

### Splice

`Splice()` actually removes the element, reindexes the array, and changes its length.

```javascript
> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]
```

> The delete method should be used to delete an object property.

## 5. map vs for loop

Use the map() function method to loop through an array’s items

```javascript
var squares = [1,2,3,4].map(function (val) {  
    return val * val;  
}); 

// squares will be equal to [1, 4, 9, 16]
```

\*\*Immutability \*\* —  The original array will be unaffected. This has potential benefits in cases where the original array is still needed elsewhere. For loops can also be written so as not to update the original array, but it requires more code and updating our new array as part of our loop operation. On the other hand map() keeps this cleaner since you only have to work in one scope to still maintain immutability

**Cleaner code** — When doing identical things, map can almost always be written with less code than for. It can be clearly written on one line sometimes whereas for requires at least two or generally three with braces included. Also, scope isolation and a reduction in the number of variables you need alongside reduced size all make code objectively cleaner.

## 6. Rounding numbers

The toFixed() method converts a number rounding to a specified number of decimals.

```javascript
var pi =3.1415;
pi = pi.toFixed(2);  // pi will be equal to 3.14
```

> NOTE :  `toFixed()` returns a string and not a number.

## 7. Use console.table

You can use `console.table` to show objects in tabular format:

```javascript
table=[{state: "Texas"},{state: "New York"},{state: "Chicago"}]
console.table(table)
```

![Table.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1625387936496/OFRRiiMdC.png)

## 8. Avoid using try-catch inside a loop

The try-catch construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.

```javascript
var object = ['foo', 'bar'], i;  
for (i = 0, len = object.length; i <len; i++) {  
    try {  
        // do something that throws an exception 
    }  
    catch (e) {   
        // handle exception  
    } 
}
```

to ⬇

```javascript
var object = ['foo', 'bar'], i;  
try { 
    for (i = 0, len = object.length; i <len; i++) {  
        // do something that throws an exception 
    } 
} 
catch (e) {   
    // handle exception  
} 
```

When an error occurs, the first one lets you continue the loop while the second one exits the loop. **The first one is suited if an exception thrown by your code is not severe enough to halt your entire program**.

## 9. Multiple condition checking

For multiple value matching, we can put all values in an array and use `indexOf()` or `includes()` method.

```javascript
if (value === 1 || value === 'one' || value === 2 || value === 'two') { 

} 
```

to ⬇

### indexOf():

```javascript
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { 

}
```

### includes():

```javascript
if ([1, 'one', 2, 'two'].includes(value)) { 

}
```

## 10. Double NOT bitwise operator (~~)

The double NOT bitwise operator is a substitute for Math.floor() method.

```javascript
const floor = Math.floor(6.8); // 6 
```

to ⬇

```javascript
const floor = ~~6.8; // 6
```

> The double NOT bitwise operator approach only works for 32-bit integers. So for any number higher than that, it is recommended to use Math.floor()

## Conclusion

I know that there are many other tips, tricks, and best practices, so if you have any ones to add or if you have any feedback or corrections to the ones that I have shared, please feel free to add them in a comment below.

Also, You can never learn from just one article. Try Google concepts and read multiple articles, play around with the code by making projects and that's the only way you learn.

Here's my final tip — **Don’t use a casual coding style. Enforce a standard**

You never know what to expect while reading the code that has a random coding style. The same coding style across the entire team and the application codebase is a requirement. It’s a boost for code readability.

***

### References

*   https://modernweb.com/45-javascript-tips-tricks-practices/

*   https://stackoverflow.com/questions/2485423/is-using-var-to-declare-variables-optional

*   https://stackoverflow.com/questions/32844818/why-i-need-to-avoid-using-try-catch-finally-inside-a-loop

*   http://rocha.la/JavaScript-bitwise-operators-in-practice

*   Cover Photo by [Juanjo Jaramillo](https://unsplash.com/@juanjodev02) on Unsplash

---

### Starting out in web development?? 💻

Checkout ▶ [HTML To React: The Ultimate Guide](https://gumroad.com/a/316675187)

This ebook is a comprehensive guide that teaches you **everything you need to know to be a web developer through a ton of easy-to-understand examples and proven roadmaps**

It contains 👇

✅  Straight to the point explanations

✅  Simple code examples

✅  50+ Interesting project ideas

✅  3 Checklists of secret resources

✅  A Bonus Interview prep

You can even check out [a free sample from this book](https://drive.google.com/drive/u/0/folders/1GJECqmBUbOwgg5eQvGlMwHcDShqxKISJ)

and here's the [link](https://gumroad.com/a/316675187) with 60% off on the original price on the complete book set ⬇

[![eBook.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1618289289910/D--w2qaO3h.png)](https://gumroad.com/a/316675187)