This blog post examines JavaScript‘s type system. It answers questions such as: Is JavaScript dynamically typed? Weakly typed? What is coercion?
An ECMAScript language type corresponds to values that are directly manipulated by an ECMAScript programmer using the ECMAScript language. The ECMAScript language types areThat has interesting consequences for constructors. Technically, they don’t introduce new types, even though they are said to have instances.
- Undefined,
- Null,
- Boolean,
- String,
- Number, and
- Object.
Even in statically typed languages, a variable (etc.) also has a dynamic type, the type of the variable’s value at a given time at runtime. The dynamic type can differ from the static type. For example (Java):
Object foo = "abc";The static type of foo is Object, the dynamic type of foo is String.
JavaScript is dynamically typed, types of variables are generally not known at compile time.
JavaScript performs a very limited kind of dynamic type checking,
> var foo = null; > foo.prop TypeError: Cannot read property 'prop' of nullMostly, however, things silently fail or work. For example, if you access a property that does not exist, you get the value undefined:
> var bar = {}; > bar.prop undefined
> '3' * '4' 12JavaScript has internal functions for performing this kind of conversion explicitly [1]. Some of them can be accessed in the language, via the functions Boolean, Number, String, Object.
> Number(true) 1 > Number('123') 123 > String(true) 'true'JavaScript’s built-in conversion mechanisms only work for the types Boolean, Number, String and Object. There is no standard way for converting an instance of one constructor to an instance of another constructor.