I've been trying to figure this out for a while but have run out of possible solutions. This is for a school assignment that is meant to create a "triangle" based on the number inputted (so if I put 3, the first line will have 1 asterisk, the second will have 2, and the third 3). The code is running fine but I'm getting an extra empty line because of the "\n" and am unsure how to remove it. My code:
function drawTriangle(size) {
let string = ""; //declares a variable string
for (let i = 1; i <= size; i++) { //loop continues upto size
for (let j = 0; j < i; j++) { //loop starts from 0 and ends at i
string += "*"; //* is added to string
}
string += "\n"; //when 1 row is finished, next line is printed on new line
}
console.log(string); //outputs the string to the console
}
As per Bergi's comment, create a local array variable and add line break at the end by using .join("/n").
Live Demo :
function drawTriangle(size) {
let str = ''; //declares a variable string
const arr = [];
for (let i = 1; i <= size; i++) { //loop continues upto size
for (let j = 0; j < i; j++) { //loop starts from 0 and ends at i
str += "*"; //* is added to string
}
arr.push(str);
str = '';
}
return arr
};
const result = drawTriangle(3).join("\n");
console.log(result);