I am really at the beginning with JavaScript and I am trying to assign a value of my object field. The value is coming from another object, but that value must be modified. It crashes if the value is null, so I need a try-catch block but I don’t know how to do it.
JavaScript
x
6
1
var marker = new google.maps.Marker({
2
3
this_one: parseInt(clients[i].fields.SomeFieldOfMyObject.replace('.', '')),
4
5
});
6
I want to convert some values that might be like “54.2” to (int) 54. But there are objects that have SomeFieldOfMyObject null and my application is crashing.
I am looking for something like:
JavaScript
1
6
1
this_one: function() {
2
try:
3
return parseInt(clients[i].fields.SomeFieldOfMyObject.replace('.', ''))
4
catch:
5
return 0 }
6
Advertisement
Answer
You can use an IIFE to run a function, where you can test the result of parsing the value and use try/catch
.
JavaScript
1
9
1
this_one: (function() {
2
try {
3
let val = parseInt(clients[i].fields.SomeFieldOfMyObject.replace('.', ''));
4
return isNaN(val) ? 0 : val;
5
} catch (e) {
6
return 0;
7
}
8
})()
9