Thoughts on coercion

Share

Thoughts on coercion

Here’s an interesting tidbit. If you’ve ever used indexOf to determine if a string contains another string (perhaps I could word this better…), then you’ve probably used something like:

var a = 'Jim';
a.indexOf('i') !== -1; // true

As you’re probably aware, if the string is not found, –1 is the return value.

A simpler and more efficient way to accomplish this test is:

var a = 'Jim';
~a.indexOf('i'); // true (coerced)

or

Boolean(~a.indexOf('i')); // true

A lot of people will state that coercion in JS is evil. I’d state that what is really evil is when people don’t know what that coercion is doing. I recently watched a video series by Kyle Simpson where he illustrated a few places where using coercion to your advantage will create simpler, easier to understand, less error-prone code. For example:

var foo; // undefined

Let’s say that foo, in this case could be undefined or null.
Using explicit coercion, our check for this value would be:

if ( foo===undefined || foo===null ) {
    // should work, all bases are covered
}

A simpler, more readable check:

if ( foo == null ) {
    // works for null or undefined
}
Share

Leave a Reply

Your email address will not be published. Required fields are marked *