let's say I have a usersList like this:
var usersList = [
{ firstName: 'Adam', lastName: 'Yousif', age: 23 },
{ firstName: 'Mohamed', lastName: 'Ali' },
{ firstName: 'Mona', lastName: 'Ahmed', age: 19 },
];
Now I want to call the map function on usersList and return a modified list like so :
var returnList = usersList.map((_user) => {
var _age;
try {
_age = _user.age;
} catch (error) {
console.log('I caught error here : ', error); // <-- not printed
_age = 'FAILSAFE-VAULE'; // <-- not set
}
var obj = {
firstName: _user.firstName,
lastName: _user.lastName,
age: _age
}
return obj;
});
I have a try-catch block inside the map function, the purpose of it is to replace the undefined property "age" of the second user with a 'FAILSAFE-VALUE'. but it doesn't work as should.
console.log(returnList);
// prints
// [
// { firstName: 'Adam', lastName: 'Yousif', age: 23 },
// { firstName: 'Mohamed', lastName: 'Ali', age: undefined }, <-- not what I want
// { firstName: 'Mona', lastName: 'Ahmed', age: 19 }
// ]
How to catch an error inside the javascript map function?
Thank you
You don't need to do try catch for that:
usersList.map((_user) => {
return {
firstName: _user.firstName,
lastName: _user.lastName,
age: _user.age || 'FAILSAFE-VAULE'
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With