Am I Your Type?

Most programming languages have a notion of type. In a very broad sense, types divide up the kinds of values that a programming language can deal with. For example, JavaScript has numbers and functions as values in addition to many other types. You can apply functions to numbers, like with f(2). But if you try to apply a number to another number, like with 2(1), you will get a TypeError to gently remind you not to be an idiot.

Every value in JavaScript has a type. Every time you do an operation the types are checked to make sure they make sense. If they don't make sense you will get a TypeError. Sometimes JavaScript will try to help and automatically convert types to make the operation succeed. For example, adding two functions returns a string that contains both functions' source code. That may or may not be what you intended...

Why bother with types? The goal of having types and checking types is to help eliminate errors in a program. The more bugs the type system can catch the better.

Static versus Dynamic

JavaScript has types that are dynamically checked. That means that the values are checked right before they are used in an operation. Here's a snippet of JavaScript showing multiple values of different types being assigned to a variable.

The alternative is for a language to be statically checked, which means programs are analyzed before being run to find type errors. In a statically checked language like C variables are declared with a single type. You can only assign values of that type to the variable.

Comparison

Dynamically type checked languages are more expressive than statically type-checked languages. There are more legal programs you can write that do what you want. As the programmer you have more options about what you can store in variables, and you can change your mind at any point in the program.

The downside of dynamic type checking is that you will only see problems when they actually occur. If some code is only rarely used, you might go a long time with a huge problem in the code. Static checking looks over the entire program to make sure the types work out before anything executes. This can help find bugs, always a good thing in my book.



Next