I am currently learning JavaScript where I found a problem that is confusing me. I tried to test "hello".indexOf("h")
and the output showed 0
which is logical. However, when I tried this "hello".indexOf("")
, the output showed 0
. How can an empty string's index is as same as the first letter?
Asked
Active
Viewed 28 times
0

Pippal B.
- 11
- 3
-
1`"hello".indexOf("he")`, `"hello".indexOf("hel")`, etc. are also at position 0. Is that also a problem? – snwflk Aug 15 '22 at 01:42
-
1I think what I'm trying to say is that all prefixes of a string are at position 0, and the empty string is a prefix of every string. – snwflk Aug 15 '22 at 01:43
-
This case is addressed in the docs on developer.mozilla.org for [String.prototype.indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf#return_value). – kofeigen Aug 15 '22 at 01:46