Includes

Checking to see if a value is inside an array is typically done with indexOf(), which rather mind-bogglingly still requires a shim, as Internet Explorer hasn’t implemented it:

var included = (array.indexOf("test") != -1)

CoffeeScript has a neat alternative to this which Pythonists may recognize, namely in:

included = "test" in array

Behind the scenes, CoffeeScript is using Array.prototype.indexOf(), and shimming if necessary, to detect if the value is inside the array. Unfortunately, this means the same in syntax won’t work for strings. We need to revert back to using indexOf() and testing if the result is negative:

included = "a long test string".indexOf("test") isnt -1

Or even better, hijack the bitwise operator so we don’t have to do a -1 comparison.

string   = "a long test string"
included = !!~ string.indexOf "test"

Get The Little Book on CoffeeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.