DEV Community

Discussion on: What happens when you IndexOf an empty string?

Collapse
 
ahferroin7 profile image
Austin S. Hemmelgarn

I suspect it originated as an implementation detail or performance optimization, and is staying around mostly for backwards compatibility.

I can't comment on C# (I've never used C# before), but in JavaScript, String.prototype.indexOf() performs a rather fast substring search for a fixed string (usually faster than the same search made with a regex in fact).

Given that behavior, it follows logically that an empty string should return index 0, because that's the first place in the string being searched that you can find an empty string (you can technically find one at every index between 0 and the length of the string). If we assume that the original implementors just thought you would never call it with an empty string (which actually makes some sense, the only case I can think of for this happening is if you're passing user input directly to indexOf()), then it would make sense that they wouldn't implement any checks for that case (and that would explain why it isn't well documented, it was thought to either be a use case that would never come up, or was thought to be self-evident).

At this point, it doesn't matter though, because it's been a language 'feature' for long enough that it can't be chanted without significant risk of breaking something.

Collapse
 
turnerj profile image
James Turner • Edited

If you were writing an IndexOf function, say it was a for-loop, you'd be comparing characters between the two strings. Comparing an empty string to any other value would be false. It would likely mean gettting to the end, not finding anything and then returning.

That said, I could see it returning 0 if the implement substring inside of IndexOf as as it might substring the length of the input and then compare two empty strings...

Still, it just feels wrong but I agree, even if people thought it was a problem, I doubt it will be fixed because of backwards compatibility.