Inside JavaScript: Understanding Type Coercion

Previous Current Next
  So, How Hard Do You Hit the Keyboard? Type Coercion: The Sensible Bits

So, How Hard Do You Hit the Keyboard?

As far as the storage of information is concerned, programming languages can be divided into two basic categories:

True, there are many more subtleties involved here than simply these two generic categories; but this is a good starting point for understanding.1

When people less familiar with programming hear that a language uses “strong typing”, they can be forgiven for thinking that something like this is going on:

Strong Typing?

The terms strong or weak typing have nothing to do with how hard you hit the keys on the keyboard; instead languages are either:

What Does It Mean to “Coerce” Something?

Coerce: Verb

To compel by force, intimidation, or authority, especially without regard for individual desire or volition

So, in the context of a programming language, who or what is being coerced?

There are two main situations in which coercion takes place:

  1. The value stored in a variable might automatically be converted (or coerced) to some other datatype
  2. The meaning of an operator might be coerced to perform a different operation than the one originally intended
    (E.G. under certain circumstances, the binary + operator might stop performing arithmetic addition and start performing string concatenation)

The point here is that this conversion happens both automatically and silently. If you’re not aware that such situations could take place, then you might find your code behaving in unexpected ways!

Type coercion exists as a direct consequence of weak type enforcement. In weakly typed languages, you are allowed to treat the data stored in a variable as if it were of some other type. (Some strongly typed languages also allow this behaviour.)

Previous Current Next
  So, How Hard Do You Hit the Keyboard? Type Coercion: The Sensible Bits


1   For a more detailed description of type enforcement in programming languages, a good place to start is the Wikipedia article on Strong and weak typing