word.includes(str) returns a boolean indicating whether or not str is included in word
word.search(str) returns a number representing the position of the first str found in word, -1 if it does not exist.
At first, I wondered why JavaScript provides both, however it's possible to create only one method that works for both cases, returns position else returns undefined, but since both exist, so it should be for a reason, maybe String.includes is faster, or maybe, it's just to make things clearer.
It looks like String.includes should be faster as it only checks if str exists rather than trying to find its position, however, my simple thought: to check if str exists in word the algorithm should loop through the word characters anyway (if there is something I'm missing let me know) and once str is found, it can easily retrieve its position, so String.includes couldn't be faster.
I want to know the real difference between them and why both exist. thank you!
string.searchis also intended to be used with regular expressions)undefinedas a return value is unconventional.if (word.something(str) != undefined)all the time. Just as weird as, but even longer than, the existingif (word.indexOf(str) > -1)orif (word.search(regex) > -1). That's whyif (word.includes(str))was created - for convenience and clarity. It has more to do with the speed of the developer writing, reading and understanding the code, than with the speed of the string search algorithm.array.find(…), unless you actually want to get the value back (andundefinedif not found). If you just want to know whether the value exists, you usearray.some(…)which appropriately returns a boolean.