Black (and White) Penguin Magic


I wrote the code below and ran it. It prints out "Hi my name is Pingu
undefined and I have 2 legs!"

I don't know why does it print undefined?

// the original Animal class and sayName method
function Animal(name, numLegs) { = name;
    this.numLegs = numLegs;
Animal.prototype.sayName = function() {
    console.log("Hi my name is " +;

// define a Penguin class
function Penguin(name) { = name;
    this.numLegs = 2;

// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();
var penguin = new Penguin("Pingu")
console.log(penguin.sayName()+" "+"and I have"+" "+penguin.numLegs+" "+"legs!");


You have an undefined because of the last line, console.log(penguin.sayName(). penguin.sayName() already causes the console to log "Hi my name is pingu".

To solve it, you can write penguin.sayName() + console.log("and I have " + penguin.numLegs + " legs!");. However, do note that the remaining sentence "and I have 2 legs!" will be sent on a new line.


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