-4

I am learning array function and came across this quiz. To get all caps from a string , first function what is possibly wrong with the second function here? Trying to find solution to this code. But could not, with the break, it works, but not with continue, what is possibly wrong with the second function here?

function getCapsWords(str) {
  let result = []; // Empty array
  const words = str.split(" "); // array
  let i = 0;
  while (i < words.length) {
    let word = words[i];
    word = word[0].toUpperCase() + word.slice(1);
    if (word === "Good") break;
    result.push(word); // populate arr
    i++;
  }
  return result.join(" ");
}

function getCapsWords(str) {
  let result = []; // Empty array
  const words = str.split(" "); // array
  let i = 0;
  while (i < words.length) {
    let word = words[i];
    word = word[0].toUpperCase() + word.slice(1);
    if (word === "Good") continue;
    result.push(word); // populate arr
    i++;
  }
  return result.join(" ");
}

getCapsWords("Hello World Good Good Morning!!!");
Barmar
  • 741,623
  • 53
  • 500
  • 612
Nava
  • 1
  • 4
  • 1
    Google "difference between break and continue" https://stackoverflow.com/questions/462373/difference-between-break-and-continue-statement/10693810 – DemiPixel Oct 07 '21 at 00:58
  • [break documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) and [continue documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue) should help. They don't do the same thing. – WOUNDEDStevenJones Oct 07 '21 at 00:58
  • `break` stops the loop, so you only return the words before `Good`. `continue` goes to the next repetition of the loop, so you just skip the word `Good`. – Barmar Oct 07 '21 at 00:58

1 Answers1

0

The problem with the second version is that you have i++ after continue. So if the current word is Good, you never increment the array index, and get stuck at that word.

You should increment the index before checking if the word is Good.

function getCapsWords(str) {
  let result = []; // Empty array
  const words = str.split(" "); // array
  let i = 0;
  while (i < words.length) {
    let word = words[i];
    word = word[0].toUpperCase() + word.slice(1);
    i++;
    if (word === "Good") continue;
    result.push(word); // populate arr
  }
  return result.join(" ");
}

Or use a for loop instead of while so the increment is not controlled by the loop body.

function getCapsWords(str) {
  let result = []; // Empty array
  const words = str.split(" "); // array
  fir (let i = 0; i < words.length; i++) {
    let word = words[i];
    word = word[0].toUpperCase() + word.slice(1);
    if (word === "Good") continue;
    result.push(word); // populate arr
  }
  return result.join(" ");
}
Barmar
  • 741,623
  • 53
  • 500
  • 612