Prototype to New Object

Hi there, I seem to have a bit of a glitch with the console.log() output at the end of the following code. The objects’ method runs and outputs as expected to the console, but, then I get an additional line containing ‘undefined’:

function Dog(name) {
  this.name = name;
}
Dog.prototype = {
  // Add your code below this line
  numLegs: 2,
  eat: function() {
    console.log("nom nom nom");
  },
  describe: function() {
    console.log("My name is " + this.name);
  }
};

let dane = new Dog("Borris the Animal");

console.log(dane.describe()); //Outputs the following two lines:
// My name is Borris the Animal
// undefined

To me, this is unexpected behaviour, I wonder if someone would be kind enough to explain what, why, how!!? It’s the type of thing that will gnore my brain to pieces, so, thank you to anyone who can help me to understand what is going on.

If a function doesn’t return anything, the return value is undefined. Nothing to do with prototypes or objects, just how functions work in JS

Hey,
The undefined comes from the console.log() that surrounds your function call
dane.describe(). It would log the return-value of the function, but since the function doesn’t return anything (instead logs already from inside describe) the outer console.log displays undefined. If you remove it, the undefined is gone.

1 Like

Hey @michaelsndr , Thank you so much, I removed the console.log() from the function and replaced it with a return and hey presto! The undefined is gone.

That was much appreciated. It would driven me doo lally tat!
Thank you again.

1 Like