aguadamuz aguadamuz - 8 days ago 4
Javascript Question

Javascript function to output string with line breaks to create a right triangle

I am taking an intro to Javascript class and am stuck on an assignment.

Write a function called drawTriangle that returns the following string. Feel free to debug-print using console.log, but make sure that the function actually returns a string.

Note that in a string, the character for a carriage return (the equivalent of hitting the “Enter” or “Return” key) is “\n”.

#
##
###
####
#####
######
#######


My initial thought was that I would use a loop to populate an array (with the hope of finding a way to output the array as a string with line breaks) but I am stuck at that point and not sure how to move forward (or if I am going in the wrong direction).

My current script is as follows:

function triangle(number) {
var triElements = [];
var pound = '#';
var rightTriangle = '';
var lineBreak = '\n';
for (var i = 0; i < number; i++) {
var rightTriangle = rightTriangle.concat(pound)
triElements.push(rightTriangle);
}
return triElements;
}

console.log(triangle(6))

Answer

using triElements.join("\n"); in your return statement

Comments