DEV Community

Cover image for JavaScript Tips and Best Practices
Apoorv Tyagi
Apoorv Tyagi

Posted on • Edited on • Originally published at apoorvtyagi.tech

JavaScript Tips and Best Practices

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:

let number = 98234567
Enter fullscreen mode Exit fullscreen mode

to ⬇

let number = 98_234_567
Enter fullscreen mode Exit fullscreen mode

And it works for any other numeric base as well:

const binary = 0b1000_0101;
const hex = 0x12_34_56_78;
Enter fullscreen mode Exit fullscreen mode

Few caveats :

  • Can not be used after leading 0.
let num= 0_12
Enter fullscreen mode Exit fullscreen mode
  • Not allowed at the end of numeric literals.
let num= 500_
Enter fullscreen mode Exit fullscreen mode

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, Airbnb’s, and jQuery’s Javascript style guides.

To know about what could happen if we rely too much on ASI, checkout the 4th issue of my newsletter 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

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined
Enter fullscreen mode Exit fullscreen mode

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.

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]
Enter fullscreen mode Exit fullscreen mode

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

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

// squares will be equal to [1, 4, 9, 16]
Enter fullscreen mode Exit fullscreen mode

**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.

var pi =3.1415;
pi = pi.toFixed(2);  // pi will be equal to 3.14
Enter fullscreen mode Exit fullscreen mode

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

7. Use console.table

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

table=[{state: "Texas"},{state: "New York"},{state: "Chicago"}]
console.table(table)
Enter fullscreen mode Exit fullscreen mode

Table.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.

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  
    } 
}
Enter fullscreen mode Exit fullscreen mode

to ⬇

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  
} 
Enter fullscreen mode Exit fullscreen mode

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.

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

} 
Enter fullscreen mode Exit fullscreen mode

to ⬇

indexOf():

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

}
Enter fullscreen mode Exit fullscreen mode

includes():

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

}
Enter fullscreen mode Exit fullscreen mode

10. Double NOT bitwise operator (~~)

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

const floor = Math.floor(6.8); // 6 
Enter fullscreen mode Exit fullscreen mode

to ⬇

const floor = ~~6.8; // 6
Enter fullscreen mode Exit fullscreen mode

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


Starting out in web development?? 💻

Checkout ▶ HTML To React: The Ultimate Guide

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

and here's the link with 60% off on the original price on the complete book set ⬇

eBook.png

Top comments (9)

Collapse
 
mvoloskov profile image
Miloslav 🏳️‍🌈 🦋 Voloskov

Nice! Never knew you could use underscores to format large numbers like that!

On semicolons though, it's only partially true. I never let production code stay without a linter, and it can catch every single of that few unintentional issues that may occur when you don't use semicolons.

When my developers like it better without semicolons, I choose not to use them, because I'd trade even the marginal improvement in their mental health for some automatable stuff all day, any day.

Collapse
 
apoorvtyagi profile image
Apoorv Tyagi

Agree. It is just that to be on safer side I'd want to use semicolon.

As I have mentioned in the links given, it can have un-intended consequences sometimes and I think that might be the reason why some companies prefer them in their coding standards.

But yeah linter are a good way to catch these issues

Collapse
 
briannarenni profile image
Brianna Renni

Good read, but I think [var] should be updated?

Collapse
 
apoorvtyagi profile image
Apoorv Tyagi

You mean in the third point? With [let]?

Collapse
 
briannarenni profile image
Brianna Renni

I believe so yes 🙂Unless I misinterpreted, up to you!

Collapse
 
pobx profile image
Pobx • Edited

Multiple condition checking => It's awesome.

Collapse
 
apoorvtyagi profile image
Apoorv Tyagi

It indeed is ;)

Collapse
 
ashishk1331 profile image
Ashish Khare😎

Bhai 3 dollars for a coffee. Kuch zada hai! Apni gali me 10 ki full chai pela denge. Par, these small tips are very useful. They say na, small milte ja large banate ja. Thanks for sharing!

Collapse
 
apoorvtyagi profile image
Apoorv Tyagi

Hahaha. Don't worry coffee optional hai ;)

Anyways thank you, Glad you find it useful.

P.S - chai pene aata hu kabhi :)