Need a little help in OOP-JS (undefined)

This code is giving “undefined” right after its successful logging…I couldn’t understand the reason for this “undefined” on last line.

function Bird(name) {
  this.name = name;
}

Bird.prototype = {
  numLegs: 2, 
  eat: function() {
    console.log("nom nom nom");
  },
  describe: function() {
    console.log("My name is " + this.name);
  }
};
let p = new Bird("cde");

console.log(p.eat()); 
// nom nom nom
// undefined
1 Like

if you are in an environment that prints the value of last line, it comes from console.log, its output is undefined

I could not understand. Why that last line is only executed with this code. Where is that line located. Why I came across this type of “undefined” very rarely. I tried it in fcc console as well as google console. What type of other environment is available ?

an environment like the browser console prints the value of the last line of the code snippet
in this case the last line is a console.log, the output of console.log is undefined

printing to the console is a side effect for console.log, not the output

It means that “undefined” like this does not matter. Am I right ?

in this case no, but you need to know that console.log returns undefined, or you can do wrong things later on

But here i have also assigned the argument to the console.log function call. How can it return undefined even then ?

sorry, it is not exactly what I said, but it is still matters

you have this one that calls p.eat()

if you look at what p.eat() does, this is its body:

it prints, but has no return statement. So you first see this being printed to the console, and you see nom nom nom

then, this one prints

and p.eat() does not return, so it returns undefined by default, and this console.log prints undefined

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