06 – Type Coercion
Operators expect certain types of values as operands. Other languages might throw an error of some sort if you try to, for example, do multiplication with strings. JavaScript however, will actually attempt to make your code work, and will do type coercion to get usable values.
Type Coercion
Type Coercion is when JavaScript has to automatically 'coerce' a value into a different type, in order that it can do what the programmer has asked.
A lot of the time, you will want coercion to occur. Sometimes however, you will not want it to happen at all.
Coercion to Numbers
true
will be coerced to1
false
will be coerced to0
""
will be coerced to 0true + true
is coerced to2
A string representing a valid number will be coerced to that number. If it contains non-number characters, such as ,
, $
, %
, or NZD
, it will be NaN
, mentioned below.
Coercion to Strings
true + " blood"
is coerced to"true blood"
false + " hope"
is coerced to"false hope"
99 + " red balloons"
is coerced to"99 red balloons"
Booleans are coerced to "true"
or "false"
respectively.
Numbers are coerced to strings as they would be output normally.
Coercion to Booleans
! 0
is coerced totrue
!! 0
is coerced tofalse
! 10
is coerced tofalse
!! 10
is coerced totrue
!! "banana"
is coerced to true!! ""
is coerced to false
0
will be coerced to a Boolean false
, every other number will be true
. ""
(empty string) is coerced to false
.
Values that coerce to true
are called truthy, and values that coerce to false
are called falsy. They're not literally true
or false
but they're not far from it.
NaN – not a number
"10 NZD" * 2
givesNaN
'$9.99' / 2
givesNaN
When JavaScript cannot do a sensible type coercion, we get the very useless value NaN
, representing a numeric value that is not a number.
While it would be much more useful to get an error when a statement like this is executed, we don't get an error, and JavaScript will carry on to the next statement.
var a = 10;
var b = "10 bananas";
var c = a * b;
console.log(c); // NaN
console.log(c + 1); // NaN;
Any operation involving NaN
results in NaN
, earning the value a reputation of being toxic.
Type Casting
Type casting is when you want to intentionally convert a value to another type, and do not wish to leave it to the whims of the interpreter.
Strings to Numbers
string * 1
This will trigger automatic number coercion as documented above.
Number(string)
parseFloat(string);
parseInt(string, 10);
These are three built-in functions that do the conversion for us. The parentheses let us pass parameters or arguments for the function to work with.
These functions can take a string beginning with a valid number and cast it to either an integer or a floating-point number.
When functions are executed, they return a value, just as a variable returns its contents. Unlike a variable, a function returns a value derived from the function's input. We can then use that value in the rest of the statement
var score = Number("12");
var averageGoals = parseFloat("2.1");
var teammates = parseInt("15", 10);
The first parameter is a string that (hopefully) has a number in it. Number()
and parseFloat()
only need the one parameter.
Aside: Number()
starts with a capital letter because the function is also the object prototype for all number values. While this will be explained more later, functions should always start with a lower-case letter, but start with a capital letter if they are object prototypes.
These functions are actually a bit more useful than the automatic type coersion, as they are a bit more liberal in ignoring any trailing non-number string characters, and thus may return NaN
less than type coersion.
For parseInt
, it takes the two parameters. The first is the same as parseFloat()
, but the second parameter is a radix: the base the number is in. Usually you want 10
for base-10, but you can use any number between 2 and 36. Always provide the radix, otherwise older browsers' JavaScript interpreters will try to guess the base of the number, and may get it wrong.
Best Practice: Use Number()
, parseInt()
and parseFloat()
on strings when you mean to work with a number value. Always provide a radix to parseInt
.
Numbers to Strings
number + ""
To coerce a number into a string, just concatenate an empty string to the number.
Numbers and Strings to Booleans
!! value
– double Boolean NOT
You may see !!
in use: this is a double NOT. !!
is often used to convert other value types to Booleans, following the automatic rules above.
!! true
is true!! false
is false
You might use !!
when coercing a truthy or lossy value into a literal Boolean true
or false
.