4

I detest using `indexOf` to check if a string contains a substring so much I could write a rant about it.

Or is there a better way? One google search later: ES6 supports `string.prototype.includes`[1]

So moral of the story: Before ranting and using something, bother to look if it is still a problem. They might have fixed it.

[1] https://developer.mozilla.org/en/...

Comments
  • 0
    Whats wrong with indexOf? It returns an integer rather than a boolean?
  • 0
    !!~arr.indexOf(thing)

    Otherwise use polyfill for .includes, Im not sure babel will cover it.
  • 0
    @AlgoRythm To me, it's counter-intuitive and clunky. I am not at all in favor of magic numbers to indicate errors. Esp. in this case with the faulty state being -1 and not 0. (And yes, it makes sense due to array index being 0. Yet I removed quite a lot of bugs pertaining to this misunderstanding from novices.) It would have been better if it throwed a catachable error.

    Beyond that I like my code to be phrased as if prose from a novel. `includes` let me do that, event though I would have preferred `contains`.
  • 0
    @k0pernikus I believe JS has find, which does throw an exception, as well as indexOf. Its been a while since I've done anything in JS. I kinda miss it.
Add Comment