25/33 Constructors in review


#1

Hello everyone,

I ended the course 25/33 entitled "Constructors in review", once clicked the blue button, the course is validated.

Here is my code:

    function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit");
    };
}

// now we can easily make all of our rabbits
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

console.log("There's 3 rabbits : \n" +
    rabbit1.describeMyself() + "\n" +
    rabbit2.describeMyself() + "\n" +
    rabbit3.describeMyself()
);

However, I notice strange things in my console display:

I am a fluffy rabbit
I am a happy rabbit
I am a sleepy rabbit
There's 3 rabbits :
undefined
undefined
undefined

First question/problem: why the beginning of the sentence "There's three rabbits" is after "I am a fluffy rabbit I am a happy rabbit I am a sleepy rabbit"?

Second question/problem: Why do I get three "undefined" at the end of console?

I really do not understand. Could you please help me ?

Thank you in advance :smile:


#2

thats because in the describeMyself() method you are calling console.log() and then you are passing that same call to console.log() again.

so this is what your call evaluates to

console.log("There's 3 rabbits : \n" +
    rabbit1.describeMyself() + "\n" +
    rabbit2.describeMyself() + "\n" +
    rabbit3.describeMyself()
);
//now becomes
console.log("There's 3 rabbits : \n" +
    console.log("I am a " + "fluffy"+ " rabbit")+ "\n" +
    console.log("I am a " + "happy" + " rabbit")+ "\n" +
    console.log("I am a " + "sleepy"+  " rabbit")
);

Now the inner console.log() calls are executed and you get the first three statements but the outer one will give undefined because the console.log() does not expect a console object or its properties and methods to passed as argument

try this

console.log("There's 3 rabbits : \n");
    rabbit1.describeMyself() 
    rabbit2.describeMyself() 
    rabbit3.describeMyself()

see the difference


#3

Indeed, I had not noticed this error ...

thank you a lot Rydan !!! :grinning: