A type can be converted in 2 different ways:
- ▪ Type casting: explicitly converting a value from 1 type to another. Occurs in statically typed languages at compile time. TypeScript example:
const myVar = otherVar as string.
- ▫ explicit: it's obvious the intent is to convert a value from one type to another.
- ▫ implicit: type conversion occurs as a side-effect of some operation.
Example, coercing a
number into a
Whenever coercion occurs, 1 or more internal operations, known as abstract operations, are performed. It always results in a primitive.
To explicitly coerce a value to a string, number or boolean, use the built-in native contructors.
new keyword isn't used (so an object wrapper isn't created).
These constructors can coerce any value to a primitive based on the rules of the abstract operations:
ToString abstract operation rules are:
- ▪ number:
"1". Very small or large numbers become their exponent form:
Object values have their own
If you implicitly coerce an object, its
toString() will automatically be called.
ToNumber abstract operation rules are:
- ▪ string:
To coerce an Object value:
- 1. The
ToPrimitive()abstract operation will check if the object has a
- ▫ if it exists & it returns a primitive value, that value will be used
- ▫ if it doesn't exist, but
toString()does, its return value will be used
- ▫ if neither exist or don't return a primitive, a TypeError is thrown
- 2. The primitive value will be coerced as per the
parseInt(..) can be used to get a numeric value out of a string containing non-numeric characters.
It parses left-to-right & stops when a non-numeric value is found.
ToBoolean abstract operation rules are:
- ▪ "" becomes
- ▪ all other values become
!!myVar can be used.
Expression operations that are implicitly coerced to a boolean:
- ▪ The test expression in an
- ▪ The test expression (2nd clause) in a
for ( .. ; .. ; .. )header.
- ▪ The test expression in
- ▪ The test expression (1st clause) in a
? :ternary expression.
- ▪ The left-hand operand to the
When comparing 2 values for equality, commonly used operators are:
- ▪ loose equality:
- ▪ strict equality:
Loose allows coercion. Strict doesn't.