I am working on a quiz for an online course.
For this quiz, you're going to create a function called buildTriangle() that will accept an input (the triangle at its widest width) and will return the string representation of a triangle. See the example output below.
buildTriangle(10); returns * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
I solved it using this function:
function buildTriangle(length) {
var line = "";
var triangle ="";
for (h = 1; h <= length; h++) {
makeLine(length);
function makeLine(length) {line += "* ";}
triangle += line + "\n";
}
return triangle
}
buildTriangle(10));
Which successfully returns:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
However, before getting to this solution, I tried this:
function buildTriangle(length) {
var line = "";
var triangle ="";
for (h = 1; h <= length; h++) {
makeLine(length);
function makeLine(length) {
for (i = 1; i <= length; i++) {
line += "* ";
}
}
triangle += line + "\n"
}
return triangle
}
console.log(buildTriangle(10));
Which returned this:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Why does this nested makeLine function not go through the loop normally (i.e. starting at 1), but instead produce 10 every time? Is there a way to force the loop to run normally (1, 2, 3, 4, 5...)? Why does this nesting not work?