Why with "console.log" gives extra "undefined"?

Hello JS guys,
I am new in JS and trying to solve a problem named [Add Methods After Inheritance] in OOP js. My solution is given below:

function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };
function Dog() { }

// Only change code below this line
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function(){console.log("Woof!");};
// Only change code above this line

let beagle = new Dog();

beagle.eat(); //gives nom nom nom
beagle.bark(); //gives Woof!

console.log(beagle.eat()); //gives "nom nom nom" and "undefined"
console.log(beagle.bark()); //gives "Woof!" and "undefined"

If beagle.bark();Woof!
but if console.log(beagle.bark()))Woof! undefined.
My qs is why that undefined in terms of console.log()? I don’t get it.

the return value from the console.log is undefined, depending on the environment you may be seeing that

1 Like

Hi…
So when you run console.log(beagle.eat());, the program runs the eat method of object beagle and then passes its return value as an argument to the function console.log

When it runs beagle.eat(), it logs to console this bit…

but then the function ends without returning a value… So the surrounding console.log() returns undefined as there is no argument passed into it…

Same as if you say console.log(x) without defining variable x…

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.