# Exercise 10- Stars

HELP >>>

here is my code

``````function showStars(num){
for (let row = 1 ; row <= num ; row++){
let pattern = '';
for (let stars = 0 ; stars < row ; stars++)
pattern+= '*';
console.log(pattern);
}
};
``````

I am trying to understand why we are using 1 in the first loop and 0 in the second?
1 min explanation didn’t work for me ;-(

What happens when you change to row = 0?

In that case the first row that is printed has no star, it’s empty. The reason for that is in the second for-loop stars is not smaller than row, it’s equal. Therefore no star is printed because pattern+= ‘*’; is not executed. Variabele pattern is still empty.

The next run row = 1 so stars is smaller than row and pattern+= ‘*’; is executed which results in one printed star.

Here’s my code, and it still works with out the second for loop…

showStars(10);

function showStars(rows) {
let stars = “”;
for (let i = 1; i <= rows; i++) {
stars += ‘*’
console.log(stars);
}
}

Just trying to understand what nesting curly braces does and how this worked without the second for loop…

The nested curly braces here…

``````for (let i = 1; i <= rows; i++) {
stars += '*';
console.log(stars);
}
``````

allow you to have two lines of codes in your for loop. Without the curly braces, your `console.log` wouldn’t be part of your loop. The nested curly braces in the first example make it possible to have a for loop within a for loop, which, as you’ve discovered, is not necessary to solve this stars problem. Yours works because you are re-using the stars list and just adding one more star each time. In the first example, they start from scratch with a new stars list each time, so they need a second for loop just to rebuild the stars. I think your solution is simpler and easier to understand.

2 Likes

Thanks for replying… as you can tell, I’m only at the beginning of my JS journey, so understanding things like this early feels important.

Just finished this exercise and also noticed my implementation used only one for loop. Thought I would come to the forum to see if anyone else came out with the same. Good job us!!

Just one loop for me too

function showStars(rows) {
let starTally = “”;
for (let i = 1; i <= rows; i++) {
starTally += “*”;
console.log(starTally);
}
}
showStars(5);