[Solved] Wrong output from a while loop using indexOf [duplicate]

Introduction

This question is a duplicate of a previously asked question. The issue is that a while loop is not producing the expected output. This can be caused by a variety of issues, such as incorrect syntax, incorrect logic, or incorrect use of the indexOf function. In this post, we will discuss the possible causes of the wrong output and how to fix them.

Solution

The problem is likely caused by the fact that the indexOf() method returns -1 when the element is not found in the array. This means that the while loop will continue to run even when the element is not found, resulting in an incorrect output.

To fix this, you can add an additional condition to the while loop that checks if the indexOf() method returns -1. If it does, the loop should be exited.

Example:

let index = 0;
while (index < array.length && array.indexOf(element) !== -1) { // code index++; }

So now the problem is that .indexOf still returns the true index of “ea” in wordTwo – it doesn’t take into account where you start from. Also, setting positionCount equal to where you find the word and then searching from that position again is just going to make you immediately find the same instance of that word, not the next one.

The index of the first instance of “ea” in wordTwo is 18, so wordTwoLength will be set to 32-18, or 14. Then you’ll find the same instance of ea in wordTwo, and wordTwoLength will be set to 14-18, or -4. Then you’ll exit the while loop, with appearances being 2.