Categories
JavaScript Best Practices

JavaScript Best Practices for Writing More Robust Code — Error Prevention

Spread the love

JavaScript is an easy to learn programming language. It’s easy to write programs that run and does something. However, it’s hard to account for all the uses cases and write robust JavaScript code.

In this article, we’ll look at ways to write more robust code when dealing with JSON and best practices when writing code to handle errors better and to prevent them from happening.

Use try…catch When Using JSON.parse or JSON.stringify

JSON.parse and JSON.stringify will throw errors if they encounter issues.

Whenever JSON.parse encounters invalid JSON in a string, it’ll throw an error. JSON.stringify throws errors when it tries to convert a circular structure to JSON.

Therefore, we should use try...catch to wrap around JSON.stringify and JSON.parse to prevent errors from stopping our program from running.

For instance, we should write something like:

try {  
  const json = '{}';  
  const parsed = JSON.parse(json);  
} catch (ex) {  
  console.error(ex);  
}

so that JSON.parse won’t crash our program when it runs into issues parsing JSON. We can also replace JSON.parse with JSON.stringify for code that uses that.

Use ESLint or Another Linter to Catching Errors Early

ESLint is a standard linter for JavaScript. It checks for syntax errors and confusing code to prevent developers from committing many kinds of problematic code or potential bugs.

It has a big list of rules which check for possible errors or useless and confusing code.

For instance, it checks for return statements in getters. This because there’s no point in having a getter that doesn’t return anything in a JavaScript or class. A getter that returns nothing is useless and it’s probably a mistake if it’s there.

Other things include disallowing the assignment operator in conditional expressions, as we probably want to use == or === to compare things instead and we forgot the extra equal sign.

There’re many more rules located at https://eslint.org/docs/rules/.

It’s easy to set up for any project. We can just install eslint in our project folder by running:

npm install eslint --save-dev

Then we create ESLint configuration file by running:

npx eslint --init

to customize the rules that we want to enable. It’s very flexible and we don’t have to enable checks for all the rules.

It also has lots of plugins to add more rules. Popular rules include Airbnb and the default rules. We can also include Node.js rules, Angular, React, Vue, etc.

Don’t Mess With Built-in Object Prototypes

We should never mess with prototypes of built-in global objects. Objects like Object , String , Date , etc. all have instances methods and variables in their prototypes which shouldn’t be messed with.

If we change them by mistake, then our code probably won’t work the way we expect them to since they often call instance methods from these built-in objects and manipulating them in our code will probably break our code.

The member of native objects may also have name collisions with members in our own code.

It’s also confusing since if we change the built-in object’s prototypes, a lot of people may think that it’s actually a method that’s part of the standard library.

We don’t want people to make that mistake and write more bad code and create more issues down the road.

Therefore, we should never modify built-in objects and their prototypes.

If we need any new functionality that built-in native objects don’t provide, then we should write our own code from scratch and reference built-in native items if necessary.

Also, if we want to use new native methods that don’t exist in the browser your app is targeting, then we can use polyfills to add that functionality instead of implementing it from scratch ourselves.

Photo by Sean McGee on Unsplash

Always Use Strict Mode

JavaScript used to let people do a lot of things that people aren’t supposed to do.

Strict mode throws errors when we write code that isn’t supposed to be written, like assign null or undefined with a value, or accidentally creating global variables by omitting var , let or const .

Other things that throw errors include trying to extend objects new properties that have the Object.freeze method applied to it.

For instance, the following will do nothing without strict mode:

const foo = {};  
Object.preventExtensions(foo);  
foo.newProp = 'foo';

However, with strict mode on:

'use strict'  
const foo = {};  
Object.preventExtensions(foo);  
foo.newProp = 'foo';

We’ll get an error ‘Uncaught TypeError: Cannot add property newProp, object is not extensible’.

It also prohibits us from using keywords and constructs that may be used in future versions of JavaScript. For instance, we can’t declare a variable called class since it’s a reserved keyword.

Strict mode is applied to all JavaScript modules by default. However, old-style scripts don’t have strict mode on by default. Therefore, we should make sure that those have strict mode on by adding 'use strict' to the top of our code.

We can also add 'use strict' inside a function, but we definitely want strict mode everywhere so we should just put it on top of the script file.

Since strict mode prevents us from committing so many kinds of errors, we should always have it on.

Conclusion

Preventing JavaScript code errors is easy with ESLint and strict mode. They prevent us from making so many kinds of errors that it’ll save us a lot time from debugging bad code.

Also, we should use try...catch to catch errors when parsing and stringifying JSON.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.