Designing a programming language: Don’t Be Clever

One lesson of programming language design? Don’t try to be too clever!

Here is an example from JavaScript​:

When you compare

0 == ‘0’

the system tries to be clever: “Comparing a number and a string? You probably meant to see whether the string contains the character ‘0’, so let’s just say ‘yes’!”, it thinks. So the result is true.

When you compare

0 == ”

it tries to be even cleverer: “Ahh, perhaps you meant to check whether the length of the string is zero! Let’s just help the user here and not require them to call a ‘length’ function. So tedious. It’s true!”

But of course

‘0’ == ”

“Comparing two strings – got it. Are they the same? No! Returning false.”

The result of all this: The fundamental property of transitivity of equality is broken in JavaScript!

a == b and b == c, therefore a == c ?

Not in JavaScript, it isn’t! How can anyone voluntarily program in a language like this?!

The lessons for me? Give me static typing any day. And don’t try to be clever when designing a language. Spelling things out is a good thing, not a bad thing.

One thought on “Designing a programming language: Don’t Be Clever

  1. > How can anyone voluntarily program in a language like this?!

    It is the most popular programming language on the planet.

    > 0 == ‘0’, 0 == ”, ‘0’==”

    That is why === exists.

    0 === ‘0’
    false
    0 === ”
    false
    ‘0’ === 0
    false

    Most experienced Javascript programmers never use == at all, or very rarely.

    == means essentially “try your best to do type conversion, then test for equality”
    — so-called “abstract equality”; there’s a very complicated (but fully-documented) set of rules for how this is done.

    === is the thing when you want exact equality.

    It could be worse. Scheme has *four* of them, =, equal?, eq? and eqv?.

Leave a Reply

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