1

I have a problem with my exercise. I have to draw something like this: https://screenshots.firefox.com/3qaHB7dcr3n610hi/jsbin.com

And this is my code

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

but with this code I can only make this:

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

I have no idea how to reverse this loop to start it from top from 5 stars, i tried something like this:

var empty = "";
for (i = 5; i <= 0;i--) {
  empty+="*";
  console.log(empty);
}

But doesn't work. Anybody know how to do this? I will be grateful :)

5
  • 5
    your condition is wrong. Should be ` i >= 0` Commented Mar 23, 2018 at 13:57
  • 1
    although that won't change the output since you still start with an empty string Commented Mar 23, 2018 at 13:59
  • i changed my condition, but still have problem with the second loop Commented Mar 23, 2018 at 14:01
  • Stackoverflow isn't a beginner's coding school. You're supposed to exhaust every single other resource first, starting with google. Commented Mar 23, 2018 at 14:03
  • check out this fiddle mate: jsfiddle.net/94La3y77/9 Commented Mar 23, 2018 at 14:08

4 Answers 4

2
  • Your approach builds the first part.
  • The second part can be accomplished using the function slice in descending direction.

var empty = "";
var i = 0;

// Build the first part
for (; i < 5; i++) {
  empty += "*";
  console.log(empty)
}

// Here i = 5, so this is the initialization for the following loop.
// Loop in descending direction using the function slice.
for (; i > 0; i--) {  
  console.log(empty.slice(0, i))
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

2 Comments

How is this useful to somebody who cannot construct a for loop?
nice one all the same ;)
1

Your condition was wrong. Check this.

for(let i = 1; i <= 5; i++) {
  console.log('\"' + '*'.repeat(i) + '\"');
}
for(let i = 5; i > 0; i--) {
  console.log('\"' + '*'.repeat(i) + '\"');
}

Comments

0

Instead of a for/loop you could use a while loop to change the direction:

let stars = 0;
let count = 0;
while (count < 9) {
  if (count < 5) stars++;
  if (count >= 5) stars--;
  const line = Array(stars).fill('*').join('');
  console.log(line);
  count++;
}

Comments

0

Just in case you need a nested for loop. (As some exercises sometimes do)

var k = 0;
for(var i = 1; i < 12; i++){   
    var stx = "";
    for(var j = k; j < i; j++){
        stx += "*";
    }
    if(i > 5) k += 2
    if(i == 6) continue
    console.log(stx);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.