Why does IndexOf return -1?

Adnan Khan picture Adnan Khan · Dec 21, 2011 · Viewed 31k times · Source

I am learning Javascript and don't understand why the indexOf below returns -1:

var string = "The quick brown fox jumps over the lazy dog";

console.log (string.indexOf("good"));

Answer

Interrobang picture Interrobang · Dec 21, 2011

-1 means "no match found".

The reason it returns -1 instead of "false" is that a needle at the beginning of the string would be at position 0, which is equivalent to false in Javascript. So returning -1 ensures that you know there is not actually a match.