Mercury
Mercury

Reputation: 13

If/Else Nested in While loop in Javascript Not Looping

As it is written, the function is only returning a single line of the song. "number" is a number inputted by the user. How do I get it to continue through the while loop until it gets to 0? I've played around with where to decrement the number (in the while condition, in each if statement, etc) but that doesn't seem to matter. Thanks for any feedback! Edited to show as array instead of string.

 var theFunction = function(number) {
  var song = [];
  while(number > 0){
    if(number > 2) {
      song.push(number + "lyrics in song.");
      number--;
    } else if(number === 2) {
      song.push(number + "different lyrics in song");
      number--;
    } else if(number === 1) {
      song.push(number + " other lyrics");
      number--;
    } else {
      song.push("End of song");
    }
    return song;
  };
};

Upvotes: 0

Views: 314

Answers (2)

Mercury
Mercury

Reputation: 13

Thank you! I had the return statement in the wrong spot. It should be:

var theFunction = function(number) {
  var song = [];
  while(number > 0){
    if(number > 2) {
      song.push(number + "lyrics in song.");
      number--;
    } else if(number === 2) {
      song.push(number + "different lyrics in song");
      number--;
    } else if(number === 1) {
      song.push(number + " other lyrics");
      number--;
    } else {
      song.push("End of song");
    }
  } return song;
}; 

Upvotes: 0

Haozhun
Haozhun

Reputation: 6511

There is no such magic that by putting return inside loop, you can get a list of return values. If you want that, you have to construct the list explicitly.

return means: Stop further execution immediately because I already know what needs to be returned. And here it is.

var theFunction = function(number) {
  var song = [];
  while(number > 0){
    if(number > 2) {
      song.push(number + "lyrics in song.");
    } else if(number === 2) {
      song.push(number + "different lyrics in song");
    } else if(number === 1) {
      song.push(number + " other lyrics");
    } else {
      song.push("End of song");
    }
    number--;
  }
  return song;
};

Upvotes: 1

Related Questions