6

Consider:

function Panda() {
   this.weight = 100;
   return [1,2]; 
}

console.log(new Panda());

When we instantiate with new keyword (new Panda()), it will returns: [1,2]

Without return statement, it returns: { weight: 100 }

function Panda() {
   this.weight = 100;
}

console.log(new Panda());

With a return statement like: return "Hello", it returns { weight: 100 }

function Panda() {
   this.weight = 100;
   return "Hello"; 
}

console.log(new Panda());

Why does it do this? Because is it must be an object?

Liam
  • 27,717
  • 28
  • 128
  • 190
André Vinícius
  • 411
  • 4
  • 12
  • 5
    It looks like returning a primitive datatype is ignored, but returning an object or array isn't. –  Jun 28 '17 at 14:18
  • 5
    If it's a constructor, why are you trying to return anything? – xdumaine Jun 28 '17 at 14:19
  • @ChrisG maybe the object can be adapted to a structure ("class"), but a primitive datatype just doesn't have indexes that can be associated with data (maybe I'm wrong). – Alejandro Iván Jun 28 '17 at 14:20
  • I can ask it different, if it is a constructor why it consider the return value? – André Vinícius Jun 28 '17 at 14:20
  • @ChrisG looks like you're [correct](https://stackoverflow.com/a/3350364/2315360) – George Jun 28 '17 at 14:20
  • 3
    You can `return Object('Hello')` but I'll be honest, I never knew returning primitives were ignored. Apparently it applies in both strict mode and non strict mode. – Patrick Roberts Jun 28 '17 at 14:21

0 Answers0