Weakly vs. Strongly Typed
Javascript is weakly/loosely typed Python is strongly typed
There is no real agreement on what “strongly typed” means, although the most widely used definition is that for strongly typed languages, it is not possible for the programmer to work around the restrictions imposed by the type system
- https://stackoverflow.com/questions/2690544/what-is-the-difference-between-a-strongly-typed-language-and-a-statically-typed
- It seems as though that’s also for statically typed languages
Strong typing in programming languages enforces strict type rules, while weak typing allows more flexibility with type conversions.
In more detail, strong typing is a concept in programming where the type of a variable is checked at compile-time, and type rules are strictly enforced.
Weak typing implies that the compiler does not enforce a typing discpline, or perhaps that enforcement can easily be subverted.
The original of this answer conflated weak typing with implicit conversion (sometimes also called “implicit promotion”). For example, in Java:
String s = "abc" + 123; // "abc123";
This is code is an example of implicit promotion: 123 is implicitly converted to a string before being concatenated with "abc"
. It can be argued the Java compiler rewrites that code as:
String s = "abc" + new Integer(123).toString();
Consider a classic PHP “starts with” problem:
if (strpos('abcdef', 'abc') == false) {
// not found
}
The error here is that strpos()
returns the index of the match, being 0. 0 is coerced into boolean false
and thus the condition is actually true. The solution is to use ===
instead of ==
to avoid implicit conversion.
This example illustrates how a combination of implicit conversion and dynamic typing can lead programmers astray.
Compare that to Ruby:
val = "abc" + 123
which is a runtime error because in Ruby the object 123 is not implicitly converted just because it happens to be passed to a +
method. In Ruby the programmer must make the conversion explicit:
val = "abc" + 123.to_s
Comparing PHP and Ruby is a good illustration here. Both are dynamically typed languages but PHP has lots of implicit conversions and Ruby (perhaps surprisingly if you’re unfamiliar with it) doesn’t.