[SOLVED] JavaScript for loop that alternates two constants

Issue

I’ve been trying to use a for loop to make a code that alternates between two strings and ends with .toUpperCase , but I’m completely stuck. I’m "able" to do it with an array with two strings (and even so it has a mistake, as it ends with the first string of the array…), but not with two separate constants.
Could anyone offer some help?

function repeteFrases(num) {
  const frases = ["frase um", "frase dois"];
  let result = "";
  for (let i = 0; i < num; i++) {
    result += i === num - 1 ? frases[0].toUpperCase() : `${frases[0]}, ${frases[1]}, `;
  }
  return result;
}
console.log(repeteFrases(2));

Solution

You’ve almost got it.. I think what you’re asking for is to repeat phrase one or two (alternating), and for the last version to be uppercase. I notice someone else made your code executable, so I might be misunderstanding. We can test odd/even using the modulus operator (%), which keeps the access of frases to either the 0 or 1 position. The other trick is to loop until one less phrase than needed, and append the last one as upper case.

function repeteFrases(num) {
  const frases = ["frase um", "frase dois"];
  //Only loop to 1 less than the expected number of phrases
  const n=num-1;

  let result = "";
  for (let i = 0; i < n; i++) {
    //Note %2 means the result can only be 0 or 1
    //Note ', ' is a guess at inter-phrase padding
    result+=frases[i%2] + ', ';
  }
  //Append last as upper case
  return result+frases[n%2].toUpperCase();
}
console.log(repeteFrases(2));
console.log(repeteFrases(3));

Answered By – Rudu

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *