0

I came accross with a question #83 in https://github.com/lydiahallie/javascript-questions

function Car() {
  this.make = 'Lamborghini';
  return { make: 'Maserati' };
}

const myCar = new Car();
console.log(myCar.make);

To my understanding the code should log 'Lamborghini'and conso;e.log(myCar().make) should log 'Maserati' But I'm totally wrong, myCar is not a function. Why?

arturasmckwcz
  • 104
  • 1
  • 7
  • 3
    "*But I'm totally wrong, myCar is not a function. Why?*" because it's an object. `new Car()` never returns a function here. – VLAZ Oct 05 '21 at 08:28
  • @VLAZ okay. If I take away ```return { make: 'Maserati' };``` then the code logs ```'Lamborghini'```. I don't understand how ```return``` affects what is returned by ```New``` statement. – arturasmckwcz Oct 05 '21 at 08:53
  • It replaces it, as long as it's an object. – VLAZ Oct 05 '21 at 09:16

1 Answers1

1

If you intend to use your function as a constructor you don't need to return anything from it. When you invoke your function with new keyword Javascript will create a new object under the hood, bind it to this and return it by default

transGLUKator
  • 642
  • 7
  • 17
  • 1
    I'm not sure how this answers the question. OP is asking how a given code behaves, not what modification to make to the code. – VLAZ Oct 05 '21 at 08:31