Advertisement
Beginner JavaScript, Error Handling

What's the difference between a built-in Error and throwing a plain string or object?

Short answer

new Error('message') creates an object with a stack trace and standard .message/.name properties, which DevTools and error-tracking tools understand. Throwing a plain string or object loses the stack trace, making debugging much harder.

Save JavaScript mock interview
Advertisement
AModel answer
new Error('message') creates an object with a stack trace and standard .message/.name properties, which DevTools and error-tracking tools understand. Throwing a plain string or object loses the stack trace, making debugging much harder.
throw new Error('Invalid input');    // has a stack trace
throw 'Invalid input';               // no stack trace, harder to debug
Real-world example
Always throwing proper Error instances (or subclasses) so production error-tracking tools like Sentry capture full context.
Likely follow-ups
  • How do you create a custom error type by extending Error?
Related topics