Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does IndexOf return -1?

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")); 
like image 536
Adnan Khan Avatar asked Dec 21 '11 06:12

Adnan Khan


2 Answers

-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.

like image 187
Interrobang Avatar answered Sep 21 '22 22:09

Interrobang


-1 means no match found. "good" is not in that sentence. This is documented behaviour.

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

like image 25
mpen Avatar answered Sep 22 '22 22:09

mpen