Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

297
Views
String is returning empty line after every input

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
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!