Search code examples
javascriptarraysundefinedfallback

JSON.parse fallback for undefined array to avoid exception


I'm parsing my array and everything is OK if it is defined:

JSON.parse(myArray);

However I get an exception in case if myArray is undefined.

What is the best fallback for it, is there anything better than this:

JSON.parse(myArray || '[]');

similar like we first verify the object to avoid an exception if undefined

if (obj) {
//do something with obj.something
}

So, is there anything shorter than

JSON.parse(myArray || '[]'); 

?


Solution

  • Your current method works just fine as well. I don't really see a reason to change it but if you feel you need to two options come to mind:

    First, you could initialize myArray with it defaulted to an empty array before it gets its values assigned.

    var myArray = '[]';
    

    Otherwise if myArray is a parameter passed to a method you are parsing it from, you can default it in the arguments section.

    function dosomething(myArray = '[]') {
        JSON.parse(myArray);
    }