0

I'm working on a piece of legacy code and found a snippet looking like this:

const createError = function(msg) {
  return new Error(msg);
};

//...

const error = new createError('Something bad happened');

I see error actually gets the return value of createError so it seems that the new keyword has no effect in this case. But how does it actually work?

Antonio Pérez
  • 6,702
  • 4
  • 36
  • 61
  • No the new keyword is working. You are creating a new `Error object`. If you `console` the `error` object, you can see that the tracestack prints that the `function` `createError` has an `Error`. `Error: Something bad happened at new createError (:2:10) at :7:15` – Burak Ayyildiz Jan 28 '20 at 12:04
  • 1
    There's no "non-constructor" functions in JS (excluding some exotics and arrow functions). Any function can be called with `new` operator, and when doing so, the function returns an object. If the value to return is not an object, it is ignored and the newly-created object is returned instead. – Teemu Jan 28 '20 at 12:09

0 Answers0