Zeyad Etman
Zeyad Etman

Reputation: 2540

"Undefined" returned at end of the function

There's "Undefined" appears at the end of the second function, i can't figure the reason. here's my code

function makeLine(length) {
    var line = "";
    for (var j = 1; j <= length; j++) {
        line += "* ";
    }
    return line + "\n";
}

// your code goes here.  Make sure you call makeLine() in your own code.
function buildTriangle(len){
    for(var i=1;i<=len; i++){
        console.log(makeLine(i));
    }
}

// test your code by uncommenting the following line
console.log(buildTriangle(10));

Upvotes: 2

Views: 78

Answers (3)

Himanshu sharma
Himanshu sharma

Reputation: 7901

Remove console at last line .There is no need of console will you call any function.

function makeLine(length) {
    var line = "";
    for (var j = 1; j <= length; j++) {
        line += "* ";
    }
    return line + "\n";
}

// your code goes here.  Make sure you call makeLine() in your own code.
function buildTriangle(len){
    for(var i=1;i<=len; i++){
        console.log(makeLine(i));
    }
}

// test your code by uncommenting the following line
buildTriangle(10)

If you want to call the function inside console.log . Then return something from buildTriangle function.

function buildTriangle(len){
    for(var i=1;i<=len; i++){
        console.log(makeLine(i));
    }
      return 'done';
}
console.log(buildTriangle(10));

Upvotes: 0

Andy
Andy

Reputation: 63524

Timo answered the why. Here's one way to fix the code so that you return the result.

Define an array and with each iteration of the loop push the result of makeLine to the array. Then return the joined array.

function buildTriangle(len){
  var arr = [];
  for (var i=1;i<=len; i++){
    arr.push(makeLine(i))
  }
  return arr.join('');
}

DEMO

Upvotes: 1

TimoStaudinger
TimoStaudinger

Reputation: 42460

If you don't explicitly return a value from a function, it implicitly returns undefined.


You log the return value of buildTriangle, which is undefined:

console.log(buildTriangle(10));

See MDN for more info.

Upvotes: 7

Related Questions