Do you skip semicolons in your Javascript code?

Do you skip semicolons in your Javascript code?

·

2 min read

Play this article

Some history

A few years back, the Javascript ecosystem got rid of the semicolons to be inserted at the end of every statement. However, this created a rift in the community as a few people embraced it whereas some were against it. To be honest, the change was quite revolutionary at that time. It enabled the JS developers to look head-to-head with Python developers.

But was this change a good idea for the Javascript ecosystem?

As time passed more and more people started realizing that bugs can appear in their code if they choose to skip semi-colons. The most common case is when you’re using a Javascript compressor to compress the code into a single line.

For example, consider the following code -

// define a function
var fn = function(){
    //......
} // missing semicolon here

// then execute some code inside a closure
(function(){
    //......
})();

This code will be interpreted by the Javascript compiler as the following -

var fn = function(){
    //......
}(function(){
    //......
})();

Conclusion

Such codes without a semicolon may create an ambiguity that may result in a devastating bug when deployed to production. This is because the Javascript parser thinks that we’re passing the second function as an argument to the first function and then tries to call the result of the first function call as a function. This results in a runtime error.

Thus, it is recommended not to skip the semicolons and rather embrace them. Further, Google’s and Airbnb’s coding guidelines also suggest using semicolons in the code to avoid such scenarios.

If you want to read their coding guidelines, their coding style guidelines are available here -

Happy Coding!

Did you find this article valuable?

Support Utkarsh by becoming a sponsor. Any amount is appreciated!