How to create this loop? Please help


#1

I’m stuck on this exercise,

Create a loop that runs five times. On the first three times and the final time it should console log ‘Hip hip hooray!’. On the fourth time, it should console log ‘And one for luck…’


#2

What have you done so far? What is it you are struggling with?


#3

Not much, I’m not quite sure how to start it.


#4

use a for loop:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for


#5

I know that it’s a for loop but not sure how to run it so that fourth time it runs a different string then back to the original string. Is it a nested for loop? do I use for/else ? this is driving me crazy


#6

You’d make a loop that iterates five times and inside it you’d have an if-statement which takes the correct action based on how many iterations have been made (yes, that means you will need to count the number of iterations so that this information is available to the if-statement)


#7

It worked! but I’m not sure if this is good code?

var tooExcited = [‘hip hip hooray’]

var feelingLucky = [‘and one for luck’]

for ( i = 0; i < 5; i++) if (i < 3) { console.log(tooExcited)} else if (i === 3)

{ console.log(feelingLucky)} else { console.log(tooExcited)}

#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.