0

If I'm returning any value(primitive of type number in this case) from a constructor function then that value is not respected and returned.

function Run() {
  this.isRunning = () => {
    return this;
  }
  return 100;
}

const obj = new Run();
console.log(obj === 100); // It should log true

Above code snippet should return true, instead it returns an implicitly created object. why is that so?

DecPK
  • 24,537
  • 6
  • 26
  • 42
  • 2
    When you use `new` in front of a function call you're going to get back an object, see the first and last step in [MDN's `new` docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new#description) – Nick Parsons Mar 19 '23 at 05:26
  • 1
    @NickParsons got it. *If the constructor function returns a non-primitive, this return value becomes the result of the whole new expression. Otherwise, if the constructor function doesn't return anything or returns a primitive, newInstance is returned instead. (Normally constructors don't return a value, but they can choose to do so to override the normal object creation process.)* – DecPK Mar 19 '23 at 05:28

0 Answers0