Search code examples
javascriptcounting

Why do i need put -1 instead of 0 to get correct code?


    let str = "Hello world";
    let target = "o";
    let pos = -1;
    while ((pos = str.indexOf(target, pos + 1)) != -1) {
      console.log( pos );
    }

When pos is - 1 it works fine, but when I set 0 and remove + 1 it returns endless 4. Why does it happen?


Solution

  • If you do not increase the position, it repeats 4 indefinitely because you are always doing the exact same check. Removing variables and using just this part:

    pos = str.indexOf(target, pos)
    

    This would mean:

    str.indexOf(target, 0) // Returns 4
    str.indexOf(target, 4) // Returns 4
    str.indexOf(target, 4) // etc
    

    That's because indexOf will start looking at the exact index that it just found so it will find the o again. Adding +1 makes sure that it continues looking PAST last occurence found.