Tuesday, November 25, 2008

A Minor Quibble with Javascript, or: Why Automatic Type Coercion is Evil

Earlier today, I posted a question to mozilla.dev.tech.js-engine, to whit:

isNaN( [1] ) = false. Why?


And got the answer I feared: it's in the spec!

As best I can follow, the spec lays out this sequence for determining whether [1] is, in fact, a number:

isNaN( [1] ) -> ToNumber( [1] ) -> ToPrimitive( [1] ) -> [1].toString() -> "1"

And "1" is coerced into a number.

Automatic coercion, of which this is a rather contorted example, produces counter-intuitive results every time. Language designers should never, ever make it core to their language. That is all.

No comments: