Coercion Flashcards
Coercion:
Does 2 + “3” == “2” + 3?
Yes. JavaScript always favors the string when combining a string and a number.
All other math operators /, *, %, - convert the string to a number.
Coercion:
Is 3 + true a valid expression in JavaScript?
Yes. It equals 4 because ‘true’ is converted to 1 by the JavaScript engine.
Coercion:
Does 3 + 4 + “5” = 3 + “4” + 5?
No. Because JavaScript evaluates left to right.
33 != 345
Coercion:
When null is converted to a number what is value?
This can mask errors!
Coercion:
When undefined is converted to a number what is its value?
NaN.
Coercion:
Is the statement
var x = NaN; x == NaN;
True or false?
False. NaN by definition is never equal to itself.
Coercion:
If and object has both a valueOf and a toString method defined. What should the toString return, the type of the object or the string representation of the value?
The string representation of the value. The avoids errors with implicit conversion.
Coercion:
What is a simple way to avoid implicit coercion and explicitly convert a value to a number?
Use the + operator.
+“123” === 123
+form.date.value === today.getDate;
Coercion:
True/False
The == operator uses implied conversion and the === does not.
True.
== attempts to coerce the values into similar type before comparison. It is usually preferable to use the === operator.