JavaScript Typing
- Weak Typing
Javascript is a weakly typed language, which means the type will be forced to change in any case that allows it. This characteristic causes many issues which can be avoided by using certain methods, and causes some instances that require manual forcing of a type to prevent Javascript’s default coercion from taking place. - Strict Equality Operator
The strict equality operator does not allow types to be coerced. This eliminates sometimes confusing results that the standard equality operator can give. Sometimes code errors can go overlooked due to a type coercion in the standard equality operator and cause errors subsequently. - Objects and Strict Equality Operator
Objects cause a different behavior in the strict equality operator—it compares for identity rather than equality. This means objects that have separate identities but contain identical information are not found equal. - typeOf
The typeOf operator gives extremely inconsistent results both within and between different implementations of JavaScript that render it essentially useless. Exception: testing for undefined variables. A declared variable will never return undefined through typeOf. - Typing with Class
Class, on the other hand, is well-defined for objects, and can function in the place of typeOf. Class is a property of an object and has no pre-defined function for accessing, so one must be written. - instanceOf
instanceOf should only be used with custom objects, as native types give unpredictable results. When using instanceOf, only custom objects originating from the same Javascript context will give correct results. - Altering types
When type coercion is needed, one may be able to explicitly force the desired type with several tricks. The built in constructors Number and String produce different types when used with the keyword ‘new’, which may require type coercion. Coercing type to a string is possible by concatenating the non-string object with a blank string. Coercion to a number type can be done using the unary plus operator (+) in front of a string. Coercion to a boolean is possible by prefixing an object with two not operators (!!).