Unclear Behaviour With `throw`and String Concatenation

Viewed 36

I have this code:

const func = () => {
  throw new Error('hey') + 'boo'
  return 'OK'
}

try {
  const val = func()
  console.log(val)
} catch (error) {
  console.log(error)
}

When launched the result is a console line: "Error: heyboo"

But this is not clear reading the code. What's the reason for this?

1 Answers

It's because you're doing new Error('hey') + 'boo' and throwing that (which may be surprising). Here's what the code is doing:

  • Creates the error object
  • Does + on the error object and 'boo', which converts the error object to string ("Error: hey") and appends "boo" to it
  • Throws the resulting "Error: heyboo" string

...which you then catch and display.

JavaScript is slightly unusual compared to other languages in that it lets you throw any value, including a string. You aren't restricted to throwing Error objects.

This code does the same thing, hopefully making it a bit clearer by breaking things into steps:

const func = () => {
    // Create error
    const error = new Error("hey");
    // Append `"boo"` to it to get a string
    const str = error + "boo";
    // Throw the string
    throw str;
    // This is never reached
    return "OK";
};

try {
    const val = func();
    console.log(val);
} catch (error) {
   console.log(error);
}

Related