0

I've just started learning javascript and I've write a code that display at the end of the output undefined? why?

var laugh = function laughs(y) {

  while (y > 0) {

    console.log("ha");
    y--;

  }

  console.log("ha!");
}

console.log(laugh(10));

And this is the output:

ha
ha
ha
ha
ha
ha
ha
ha
ha
ha
ha!
undefined
j08691
  • 204,283
  • 31
  • 260
  • 272
J.Doe
  • 35
  • 1
  • 4
  • Possible duplicate of [Does every Javascript function have to return a value?](https://stackoverflow.com/questions/17337064/does-every-javascript-function-have-to-return-a-value) – Tsvetan Ganev Jan 26 '18 at 19:39

3 Answers3

2

laugh doesn't return anything and by default a function will return undefined, and that will pass into your last console.log call.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

Because the function laugh doesn't return any value, so the result is undefined.

Look the modification to return "HELLO", this is just to illustrate.

var laugh = function laughs(y) {
  while (y > 0) {
    console.log("ha");
    y--;
  }

  console.log("ha!");

  return "HELLO";
}

console.log(laugh(10));
Ele
  • 33,468
  • 7
  • 37
  • 75
0

laugh() does not explicitly return a value; therefore its return type is undefined. You're calling laugh() from within a console.log() - the result being that you see all the console.log() calls that occur within laugh() then, additionally, the undefined being returned by laugh() is being logged to the console.

You could return a string if you want to log the result of the function. Something like this:

var laugh = function laughs(y) {
  var str = '';
  while (y > 0) {
    //console.log("ha");
    str += 'ha\n';
    y--;
  }
  //console.log("ha!");
  str += 'ha!\n';
  return str;
}

console.log(laugh(10));

Alternatively, you could just remove the console.log() enclosing the function call like this:

var laugh = function laughs(y) {
  while (y > 0) {
    console.log("ha");
    y--;
  }
  console.log("ha!");
}

laugh(10);
Tom O.
  • 5,730
  • 2
  • 21
  • 35