Skip to content
Advertisement

How does one avoid or suppress code exceptions while trying to assign an object value via exactly one expression

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.

 var marker = new google.maps.Marker({
            ...
            this_one: parseInt(clients[i].fields.SomeFieldOfMyObject.replace('.', '')),
            ...
        });

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:

  this_one: function() { 
               try: 
                  return parseInt(clients[i].fields.SomeFieldOfMyObject.replace('.', ''))
               catch:
                  return 0 }

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.

this_one: (function() {
    try {
        let val = parseInt(clients[i].fields.SomeFieldOfMyObject.replace('.', ''));
        return isNaN(val) ? 0 : val;
    } catch (e) {
        return 0;
    }
})()
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement