Markcce Eros Markcce Eros - 14 days ago 4
Javascript Question

Javascript map show error message if undefined instead of breaking

I'm having an issue where the console is giving me the following error:

TypeError: myData.names is undefined


and here is the code:

var myvar = myData.names.map(function (value) {
return [value.name, 1];
});


When I get this error the code just breaks so the rest of the code will stop working.

What can I do so that the user gets an alert instead and the code doesn't break the whole of the page?

Answer

You can check if myData is not undefined or put your code in try catch block

try{
    if(myData && myData.names){

            var myvar = myData.names.map(function (value) {
                return [value.name, 1];
            });

      }
   }
     catch(ex){
        console.log(ex.toString();
    }
Comments