Static vs. Dynamic Typing
JavaScript is a dynamically-typed language. This means that you don't have to
specify a variable's data type when you declare it, for example with an int
,
string
, array
, etc. Furthermore, you can even change a variable's data
type on-the-fly. This behavior will be familiar to programmers who know other
dynamically-typed languages like Python or Ruby, but strange to those who only
know statically-typed languages like Java or C#.
There is a bit of a rivalry between advocates of statically-typed and
dynamically-typed languages. Advocates of statically-typed languages argue
that declaring types beforehand helps eliminate type-related bugs, and ensures
the final product is faster and more efficient. Advocates of dynamically-typed
languages appreciate how much quicker it is to prototype and rapidly-iterate
their code, and they argue the risk of type-related bugs is overstated. My own
view is that you should pick the right language for the job, whether that be
statically- or dynamically-typed. Since JavaScript's Web Audio API is
excellent for dealing with audio, we use JavaScript, regardless of the merits
of its typing.
Strong vs. Weak Typing
Even though Python and Ruby are dynamically-typed languages, they are also
strongly-typed languages. This means that if a function or operator expects
one type, and receives data of a different type, the program will throw an
error. JavaScript, on the other hand, is weakly-typed, which means that if a
function or operator expects one type, it will forcefully and secretly cast
whatever it receives to that type. While at first this may seem like a welcome
convenience, in practice it introduces a cavalcade of unwanted and hard-to-spot
bugs.
Here's an example: the number 4
times the string "2"
gives you the
number 8
. However, the number 4
plus the string "2"
gives you the
string "42"
. JavaScript gives you no warning these type conversions have
taken place. This trap is particularly easy to fall into when asking a user to
type in a number in a form on a web page. Since web forms spit out strings by
default, you'll need to remember to specifically cast user responses to
integers. For this, use the
Number()
function.
==
vs. ===
Another unfortunate aspect of JavaScript's weak typing system is the ==
or
"double-equals" operator. Double-equals will also cast its operands. This
leads to some truly bonkers equivalencies, from the more benign "2" == 2
, to
the crazier false == "0"
and " \t\t\r\n " == 0
. Double-equals also
lacks transitivity: false == undefined
is false, false == null
is false,
but null == undefined
is true.
Luckily, JavaScript provides alternatives to this madness: ===
and its
opposite, !==
, which act just like ==
and !=
in every other language.
You should exclusively use the triple-equals operators in your code.