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"));
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"));
-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.
-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.
Because arrays are 0 based, returning 0 would mean starting from the first character was matched; 1, the second character, and so on. This means anything 0 and up would be a true or "found" response. To keep everything in the integer category, -1 signifies no match found.
There is another reason for indexOf to return -1 when no match is found. Consider the code below:
if (~str.indexOf(pattern)){
console.log('found')
}else{
console.log('not found')
}
Because ~(-1) = 0 so the fact that indexOf returning -1 makes it easier to write if...else using ~.
The search never finds what it's looking for ("good" isn't in the sentence), and -1 is the default return value.
Related issue; even if the subject word exists in the sentence (semantically speaking) or any sequence of letters matching partially, indexOf() would return the index of its first matching letter. e.g.
const string = "The quick brown fox jumps over the lazy dog";
console.log(string.length);
// expected output: 43
console.log (string.indexOf("fox"));
// expected output: 16
console.log (string.indexOf(" q"));
// expected output: 3
But if the partial sequence of letters is not matching any part of the string array, the method will return -1, the same case with "good";
console.log (string.indexOf("foxy"));
// expected output: -1
console.log (string.indexOf("good"));
// expected output: -1
Just in case, turning it to an array of sub-strings (here the words) is possible with split() method, splitting the long string by its spaces (punctuations);
const words = string.split(' ');
console.log(words);
// expected output: ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
console.log(words.indexOf("fox"));
// expected output: 3
© 2022 - 2024 — McMap. All rights reserved.
0 === false
JS returnsfalse
(same withundefined
andnull
), so there doesn't seem to be any reason why use-1
, since you can check all those more intuitive values. JS arelady has two "empty" values -undefined
andnull
, why not use of those?. – Pyroelectric