How to avoid common errors in Javascript
Introduction
- Now we have learned about error types and how to debug the errors
- Now there is a standard way of coding which can help in avoiding most of the common error types like ReferenceError and TypeError
Use try-catch block
To avoid errors that stop your applications, we can use the try-catch block as follows
const person = (param) => { if (!param) { throw Error('Param is required'); } let home = param.adress.home; return home; }; let personDetails = { email: 'John@test.com', address: { home: '#623 street' } }; try { let homeAddress = person(personDetails); console.log(homeAddress); } catch (e) { console.log(e.message); } // output // Cannot read property 'home' of undefined
Check for empty values
As we can observe in the above code snippet, we can check the param is empty or not with if
const person = (param) => { if (!param) { throw Error('Param is required'); } let name = param.name; return name; }; let personDetails = { name: 'John' }; let name = person(personDetails); console.log(name); // output // john
Check if a property exists
Without checking the property and accessing it, throws a below error
//Checking if a property exists and accessing it: const person = (param) => { if (!param) { throw Error('Param is required'); } let home = param && param.adress && param.adress.home; return home; }; let personDetails = { email: 'John@test.com', address: { home: '#623 street' } }; let homeAddress = person(personDetails); console.log(homeAddress); // output // undefined