-3

Recently I have attended one interview, Interviewer asked one interesting question have a look

 function MyClass(){
        this.a = 10;
        return 20; // Interesting part
    }
    
    var obj1 = new MyClass();
    console.log(obj1.a); //  10 works as expected.
    console.log(obj1.constructor()); // 20 later I found this

how will you access return value(20) from obj1?

I found the answer after looking proto of the obj1. obj1.constructor() Works as expected

Please help me to understand this.

Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37

1 Answers1

4

See mdn:

The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

The 20 goes nowhere and cannot be accessed. It isn't an object, so the instance of MyCass is returned instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335