Search code examples
javascriptswitch-statementcustom-errors

How to represent Get error type using a switch statement?


How to represent the following using a switch statement?

if (e instanceof EvalError) {
    console.log(e.name + ': ' + e.message);
  } else if (e instanceof RangeError) {
    console.log(e.name + ': ' + e.message);
  }

Solution

  • While switch is using strict comparison, you could take true as expression and the other test as value for testing.

    switch (true) {
        case e instanceof EvalError:
            console.log(e.name + ': ' + e.message);
            break;
        case e instanceof RangeError:
            console.log(e.name + ': ' + e.message);
            break;
    }