1

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 }
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
learner123
  • 165
  • 10

2 Answers2

1

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;
    }
})()
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • This seems to be a good solution, but replace throws exception, ((index):213 Uncaught TypeError: Cannot read property 'replace' of null), could you provide a solution for this? – learner123 Sep 22 '20 at 19:18
  • Sorry, I thought you were trying to detect the error from `parseInt`, forgot about the property access. – Barmar Sep 22 '20 at 19:19
1

I will take the OP by the name (@learner123) and give some other thoughts about the usage of try...catch. There are pros and cons. Some argue that try-catch has to be avoided in performance critical functions and within loops. Some will hint that one always should aim for readable code (as a pro argument for not having to change code towards checking by guards or by a lot of if ... else statements). Thus, since one does already know, where and for which reason the code will fail, one might favor the defensive programming approach ...

this_one: (() => {
  // always assure a string value ... (null || '').
  const str = (clients[i].fields.SomeFieldOfMyObject || '');
  // do not forget to pass the radix to `parseInt`.
  const num = parseInt(str.replace('.', ''), 10);
  return Number.isNaN(num) ? 0 : num;
})()
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
  • 1
    I really appreciate the explanation and it's a nice solution for my problem. I will take care of your advice of using defensive programming in my js code. – learner123 Sep 22 '20 at 22:49