Câu hỏi phỏng vấn Javascript
Câu hỏi

What's the difference between throw Error('msg') vs throw new Error('msg') ?

Câu trả lời

In JavaScript, both throw Error('msg') and throw new Error('msg') are used to generate and throw errors, but there are subtle differences in how they operate and their implications.

  1. Factory Function vs Constructor:

    • Error('msg') acts like a factory function. This means it returns a new error object each time it is called, regardless of whether you use the new keyword with it or not[1].
    • new Error('msg') explicitly uses the Error constructor to create a new error object. Using new ensures that the error object is an instance of Error[1].
  2. Implications of using new:

    • When you use new Error('msg'), it is clear that you are creating a new instance of an error, which is the typical and recommended way to handle errors in JavaScript. This usage ensures that the prototype chain is correctly set up, and the error instance inherits all methods from Error.prototype[1][3].
    • Using Error('msg') without new might lead to confusion or errors in a program if the code checks for specific instances of errors using instanceof. Although in most modern JavaScript environments, Error('msg') and new Error('msg') behave similarly, explicitly using...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between a shim and a polyfill?

junior

What is a Polyfill?

middle

What is the preferred syntax for defining enums in JavaScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào