Javascript Type Coercion
// JavaScript - Type coercion
// After a string all the + will be treated as string concatenation operator
(not binary +). "10"+20+30 will produce "102030"
// General guideline for addition operators:
1. Number + Number -> Addition
2. Boolean + Number -> Addition
3. Boolean + Number -> Addition
4. Number + String -> Concatenation
5. String + Boolean -> Concatenation
6. String + String -> Concatenation
// Rules for coercion:
1: undefined == null
2: If one operands is string another is number, convert string to number
3: If one is boolean and another is non-boolean, convert boolean to number and
then perform comparison.
4: While comparing a string or number to an object, try to convert the object to
a primitive type and then try to compare.
5: NaN, null and undefined will never === another type. NaN does not even === itself.
Type-casting is about converting a variable from one type to another. For
example, converting a variable from a string to an integer. JavaScript
automatically does type-conversion. However, sometimes, perhaps for some old
browser, we may need to give it a nudge. I don't remember the exact circumstance
that I had to do this though. Adding an empty string to a variable is useful way
of converting it to a String. Using the parseInt function is a way to convert a
string to an integer.
page revision: 4, last edited: 14 Nov 2016 19:40