Imagine having a list of users like the following:
var usersList = [
{ firstName: 'Adam', lastName: 'Yousif', age: 23 },
{ firstName: 'Mohamed', lastName: 'Ali' },
{ firstName: 'Mona', lastName: 'Ahmed', age: 19 },
];
Now, you want to use the map function on the usersList to create a modified list as shown below :
var returnList = usersList.map((_user) => {
var _age;
try {
_age = _user.age;
} catch (error) {
console.log('An error was caught here : ', error);
_age = 'FAILSAFE-VALUE';
}
var obj = {
firstName: _user.firstName,
lastName: _user.lastName,
age: _age
}
return obj;
});
You have implemented a try-catch block within the map function to replace any undefined "age" property of the second user with 'FAILSAFE-VALUE'. However, it is not functioning correctly.
console.log(returnList);
// prints
// [
// { firstName: 'Adam', lastName: 'Yousif', age: 23 },
// { firstName: 'Mohamed', lastName: 'Ali', age: undefined },
// { firstName: 'Mona', lastName: 'Ahmed', age: 19 }
// ]
Is there a way to effectively handle errors within the javascript map function?
Your insights are appreciated.