Simpler Ways To Avoid ReferenceErrors & TypeErrors In Your JavaScript CodesteemCreated with Sketch.

in #javascript5 years ago (edited)

 JavaScript is amazing and it can do wonders if used efficiently. Most of us know JavaScript and even the deepest parts of it but not all of us are able to write robust and reliable code. The code of that level requires some thinking, reading, and understanding of other’s professionals' code.

Today, I want to share my thoughts on ReferenceErrors and TypeErrors that happens quite frequently in JavaScript. How to avoid it? Is there a better way to avoid these? Well, yes, instead of going through writing deep and nested structure of if/else for validations of objects, we write it in a single line of code.



Let’s first understand, what is a ReferenceError? An error occurs when we try to access an undeclared variable and A TypeError occurs when the variable exists, but the operation we are trying to perform is not appropriate for the type of value it contains. e.g open up your browser console and try accessing a variable like this

 a  // Uncaught ReferenceError: a is not definedwindow.a.b.c  // Uncaught TypeError: Cannot read property ‘b’ of undefined 

How to avoid a ReferenceError variable?

a // Uncaught ReferenceError: a is not defined

Instead of directly accessing it, as shown above, we need to check whether a has been declared or not. We can use typeof, It helps us to find the typeof variables and for an undeclared variable, it gives us undefined for undeclared variables.


const b = (typeof a !== "undefined") && (a) || undefined
b  // undefined


Now, JavaScript Engine, instead of throwing the error, it checks first whether the variable a has any type and if not then return undefinedWe should use this terminology wherever they are going to be used especially closures. e.g adding typeof window is considered as good practice before using window object. Even GatsbyJs don’t let you generate a build without typeof for global/closure variables.


How to avoid a TypeError for an object?

const obj = {
 steem: {
   price: 0.14,
   currency: '$',
   users: ['funnyman', 'steemit']
 },
 eos: {
  price: 3.6,
  currency: '$',
  users: ['dan']
 }
}
obj[‘btc’].price // Cannot read property ‘price’ of undefined


We need to have some validations in place to avoid halt of execution of the code. Again, we will make use of typeof and && or || operators


const priceBTC = (typeof obj === "object" && ((obj["btc"] || {}).price || 0) || 0)


Let’s go step by step


typeof obj === "object" || 0


It checks if the declared obj is an object or not and it checks the other validations if it is true else it returns 0


(obj["btc"] || {})


Now, after confirming we have an object with us, we check for the property which we want to access i.e “btc”If “btc” is present in the object, it will return the object else it will return undefined which would ultimately make the expression to return an empty object after going through the || (OR) condition.


(obj["btc"] || {}).price || 0


Now, we either have an empty object or the actual object with data. So now we check if “price” property is present and if it then returns the price else return undefined which would make the expression to return 0 after going through the || (OR) condition.

With Destructuring assignment

You can go as much complex as you want with these operators and with destructuring, it really takes the lead.


const { btc: { price: btcPrice = 0 } = {} } = (typeof obj === "object" && obj) || {}
btcPrice // 0


It just makes so much sense to have all the validations as condensed and as cohesive as possible. If we would have done all these validations with if/else, each validation would have taken at least 4 lines of code. We have added 3 validations in our single line of code which would have been at least 10 lines of code. We can have as many validations as needed. Smart use of these operators makes our code so much robust, precise and easy to read.

This blog has also been published on Medium - Here is the link :  https://medium.com/@chandna.vishal1234/simpler-ways-to-avoid-referenceerrors-typeerrors-in-your-javascript-code-3bab7dd06710 

Thanks for reading this blog and if you think you get some value out of it then please give it a thumbs up :)

Coin Marketplace

STEEM 0.27
TRX 0.13
JST 0.032
BTC 61451.22
ETH 2929.56
USDT 1.00
SBD 3.65