-1

I am new to JavaScript. I want to print this star pattern using console.log() in JavaScript

*
* *
* * *
* * * *
* * * * *

I tried this code

for(var i=1; i <= 5; i++)
{
  for(var j=1; j<=i; j++)
  {
   console.log('*');
  }
}

Each * is getting printed on a separate line.

Kindly help. Thanks :)

2
  • Check out this answer: stackoverflow.com/questions/33089739/… Commented Jun 2, 2021 at 16:53
  • In the future, before posting a question, you might want to do a search. For example, for this question, try googling for "console log same line" - you'll find many relevant answers on stack overflow Commented Jun 2, 2021 at 16:54

4 Answers 4

3

I guess this code works

let star = "\n";

for(var i=1; i <= 5; i++)
{
  for(var j=1; j<=i; j++)
  {
   star += '*'
  }
  star += "\n";
}

console.log(star);

It outputs

"
*
**
***
****
*****
"
Sign up to request clarification or add additional context in comments.

Comments

1
for(var i=1; i <= 5; i++)
{
  let startStr = '';
  for(var j=1; j<=i; j++)
  {
    startStr += '* '
  }
   console.log(startStr.trim());
}

Comments

1

I believe that in regular JavaScript there is no way of printing to the console without a trailing newline, so instead, I'd suggest the following code

for(var i=1; i <= 5; i++){
    let finalString = ""
    for(var j=1; j<=i; j++){
      finalString += "* ";
    }
    console.log(finalString)
}

which saves the lines to a variable before printing them, removing the newline between them. Another option might be

var finalString = ""
for(var i=1; i <= 5; i++)
{
    finalString += "* "
    console.log(finalString)
}

which doesn't use nested loops but does a similar thing to the previous one, just more efficient.

Comments

1

This is little bit tricky try out this -

use string.repeat function

let star = "*";
    for (var i = 1; i <= 5; i++) {
        console.log(star.repeat(i));
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.