Build a Pyramid Generator - Build a Pyramid Generator

Tell us what’s happening:

My code seems to run correctly except that each time it prints “undefined” before the correct pyramid, and therefore the tests won’t pass.

I’ve done some Googling and it says that “undefined” will appear in the console if the function doesn’t return anything when called, but I have a return statement at the end of my function, so I’m a bit confused about what’s happening here?

I’ve used JSON.stringify which confirmed that my pyramids are correct, it’s just the “undefined” that’s stopping the tests from passing.

Thanks in advance for your help!

Your code so far

function pyramid(string, num, bool) {

  // Find longest row of the pyramid
  let longestLine = 2*num-1;
  let shortestLine = 1;
  let result;

  // Create string for empty space
  let empty = " ";

  if (bool == true) { // APEX DOWN
    for (let i = 0; i < num; i++) { 
      result += "\n" + empty.repeat(i) + string.repeat(longestLine);
      longestLine = longestLine - 2;
    }
  } else if (bool == false) { // APEX UP
    for (let j = num; j > 0; j--) { 
      result += "\n" + empty.repeat(num-1) + string.repeat(shortestLine);
      num = num - 1;
      shortestLine = shortestLine + 2;
    }
  }
   return result;
}

console.log(pyramid("o", 4, false));


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0

Challenge Information:

Build a Pyramid Generator - Build a Pyramid Generator

The undefined appears to be part of the returned result itself - at the beginning of the result variable. How it could got there?

What is the value of result here? You are concatenating that value to your output.

Ohh I think I understand, because the initial value of result is undefined, that prints as well as the pyramid.

I changed let result; to let result = ""; and now the undefined has disappeared!

Thanks so much for your help!

I didn’t even consider that – thanks for your help!

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