0

I have this case where I want to run code that may have an error but I don't need to catch it.

If the response is not valid JSON then the result should be 0:

I'd like to use this code:

var overallProgress = try {JSON.parse(text)} ? 0; 

Is it possible to the above?

Or something like this:

var overallProgress = try { JSON.parse(text)} catch(error) { 0 }; 
var overallProgress = try { JSON.parse(text)} catch(error) { overallProgress = 0 }; 

There are errors using the code above.

I found this related post below but no answer.

Is try {} without catch {} possible in JavaScript?

For anyone whose eyes I've hurt:

var overallProgress = 0; 
try { overallProgress = JSON.parse(text).overallProgress } 
catch(error) { overallProgress = 0 }; 
1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231

1 Answers1

1

Not directly, no. But you can use an IIFE:

const overallProgress = (() => { try { return JSON.parse(text) } catch { return 0 } })();

I'd still format it as multiple lines though:

const overallProgress = (() => {
  try {
    return JSON.parse(text);
  } catch {
    return 0;
  }
})();

Apart from being able to use const, it doesn't really have an advantage over simply using two assignments:

let overallProgress;
try {
  overallProgress = JSON.parse(text);
} catch {
  overallProgress = 0;
}

or even

let overallProgress = 0;
try {
  overallProgress = JSON.parse(text);
} catch {
  /* ignore: keep `overallProgress` value */
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375