Typing: Strong, Weak, Static, and Dynamic

Typing: Strong, Weak, Static, and Dynamic

A quick comparison of strong vs weak typing, and static vs dynamic typing, with relevant examples

A friend of mine used to absolutely smash the keyboard every time he used to code. When questioned he always had the same reply: "I'm coding in a strongly typed language".

While trying to find out more about what made a language's typing "strong" or "weak", I realized that there's no precise technical definition that's accepted everywhere. Still, here's what seems to be widely agreed upon.

Weakly Typed Languages

In a weakly typed language, the language allows the programmer to work around the type system, meaning that values of certain types can be used as values of other types. Here's some code from C for example:

double pi = 3.1415;
double *dPtr = π

int *iPtr = (int *)dPtr;
printf("%d", *iPtr); 
// prints out -1065151889

The above code compiles without the slightest murmur from the compiler.

And here's a more modern example from JavaScript:

("b" + "a" + + "a" + "a").toLowerCase()
// evaluates to "banana"

Weakly typed languages perform a lot of these implicit conversions as illustrated in the above example. +"a" evaluates to NaN, which becomes the string "NaN" during concatenation.

Strongly Typed Languages

In contrast, strongly typed languages do not allow the programmer to get away with this sort of manoeuvring. In the below code, Python refuses to treat the number 5 as anything except a number.

num = 5
string = "abc"
print(num + string) 
# TypeError: unsupported operand type(s) for +: 'int' and 'str'

Static vs Dynamic Typing

What about static and dynamic typing then? While many feel that the terms "strong" and "weak" typing are subjective, static and dynamic typing seem to be pretty well defined.

In statically typed languages, variables have types. In dynamically typed languages, values have types.

When a language is statically typed, it allows a lot of minor bugs to be detected well before the program is run. The compiler of a statically typed language can perform checks to ensure that the right types are going into the right places in the program.

Dynamically typed languages allow variables to be flexible. You can reassign the same variable to values of different types throughout the program. This comes at the cost of ending up with values of unexpected types in your code when you're not careful.

Combinations

We end up with four possible combinations of language classifications, and here are examples for each of them.

Strong, Static: Java, C#

Strong, Dynamic: Python, Ruby

Weak, Static: C, C++

Weak, Dynamic: JavaScript, PHP

So to sum up, strong vs weak typing and static vs dynamic typing are two orthogonal ways of classifying languages. Strongly typed languages do not allow loopholes in the type system, while statically typed languages enforce that variables have an associated type.