JavaScript is quick to convert one type of value into another, sometimes helpfully and sometimes not. After this lesson you will know the rules well enough to convert deliberately, spot the common traps, and compare values safely.
Two kinds of conversion
- Explicit conversion is when you ask for it, with
String(x),Number(x)orBoolean(x). - Implicit conversion is when JavaScript does it behind your back, because an operator needs a different type.
Do the first kind whenever you can. It is easier to read and has no surprises.
Converting to a string
console.log(String(42)); // 42
console.log(String(true)); // true
console.log(String(null)); // null
console.log(String(undefined)); // undefined
console.log(String([1, 2])); // 1,2
console.log((42).toString()); // 42All of these give text. String() is the safest, because null.toString() would throw an error while String(null) does not.
Converting to a number
console.log(Number(" 12 ")); // 12 spaces around are ignored
console.log(Number("1e3")); // 1000
console.log(Number("")); // 0
console.log(Number("12abc")); // NaN
console.log(Number(null)); // 0
console.log(Number(undefined));// NaN
console.log(Number(true)); // 1
console.log(Number([])); // 0
console.log(Number([5])); // 5The rule of thumb: if the whole text looks like a number, you get it, and otherwise you get NaN. The quirk to remember is that an empty string, and a string of only spaces, becomes 0, so check for empty input before converting. parseInt and parseFloat are more forgiving: parseInt("12abc") is 12.
Converting to a boolean
Boolean(x) answers "is this value truthy?". There is a short list of falsy values, and everything else is truthy.
Falsy: false, 0, -0, 0n, "" (empty string), null, undefined, NaN.
console.log(Boolean("")); // false
console.log(Boolean(" ")); // true a space is still text
console.log(Boolean(0)); // false
console.log(Boolean("0")); // true non-empty string
console.log(Boolean([])); // true even an empty array
console.log(Boolean({})); // true
console.log(Boolean(NaN)); // falseThe Control flow section builds on this when you write if statements.
Implicit conversion with operators
The + operator is the main trap. If either side is a string, it concatenates.
console.log("5" + 3); // 53
console.log(1 + 2 + "3"); // 33 left to right: (1 + 2) first, then join
console.log("1" + 2 + 3); // 123 join first, so everything is textThe other arithmetic operators go the other way: they convert to numbers.
console.log("5" - 3); // 2
console.log("5" * "2"); // 10
console.log("a" * 2); // NaN
console.log(+"7"); // 7 a unary plus converts to a number
console.log(+""); // 0
console.log(1 + null); // 1
console.log(1 + undefined); // NaN
console.log(true + true); // 2You will see +value used as a quick way to convert text to a number, but Number(value) says what it means.
Here is the classic real-world bug, with the fix:
<pre id="out"></pre>
<script>
// Text from an input box is always a string.
const input = "15";
const wrong = input + 5; // joins the text
const right = Number(input) + 5; // converts first
document.getElementById("out").textContent =
"input + 5 = " + wrong + "\n" +
"Number(input) + 5 = " + right;
</script>It prints 155 and then 20. Whenever you read numbers from a form, convert them straight away.
Equality: == versus ===
JavaScript has two kinds of equality.
===(strict) is true only if the type and the value are both the same.==(loose) tries to convert the types first, then compares.
console.log(1 == "1"); // true
console.log(0 == ""); // true
console.log(0 == "0"); // true
console.log("" == "0"); // false even though both equal 0
console.log(null == undefined);// true
console.log(null === undefined); // false
console.log(NaN == NaN); // false
console.log([] == false); // true
console.log("1" === 1); // falseLook at the third and fourth lines: 0 == "" and 0 == "0" are both true, yet "" == "0" is false. Loose equality is not even consistent from line to line. That is why nearly every style guide says to use === and !== always. A frequently quoted exception is value == null, which is true for both null and undefined, but writing the two checks out is clearer for a beginner.
Two special cases of ===:
NaN === NaNisfalse. UseNumber.isNaN(value).Object.is(NaN, NaN)istrue, andObject.is(0, -0)isfalse, while0 === -0istrue. You rarely needObject.is.
Objects and arrays compare by identity
const a = { x: 1 };
const b = { x: 1 };
console.log(a == b); // false
console.log(a === b); // false
console.log(a === a); // trueTwo separate objects are never equal, even with identical contents. They are equal only when both names point to the very same object, as the Data types lesson explained. To compare contents, compare their properties one by one, or compare their text forms in simple cases.
Comparing across types
Be careful with < and > too.
console.log("10" > "9"); // false both text, compared character by character
console.log(10 > "9"); // true one number, so "9" becomes a number
console.log("abc" > 5); // false "abc" becomes NaN
console.log(null >= 0); // true
console.log(null > 0); // falseThe last two show again why conversions are hard to guess. Convert your inputs to the type you want before comparing.
Common mistakes
- Adding numbers read from a form. The values are strings, so
+joins them. Convert withNumber(). - Using
=="because it works". It works until it does not. Use===. - Trusting
Number(""). It is0, notNaN. Check for an empty value first. - Thinking
"0"and[]are falsy. They are truthy. - Comparing arrays or objects with
===for their contents. Compare element by element instead. - Using
parseIntfor everything. It silently ignores trailing junk, soparseInt("12abc")passes.
Exercise
- Without running it, predict the result of each:
"3" + 4,"3" - 4,"3" * "4",true + 1,[] + []. Then run them and check your guesses. - Make
const ageText = "29";and compute the age next year as a number. - Write a check that
userInputis a valid, non-empty number: not empty, and notNaNafterNumber(). - Print
0 === false,0 == falseandnull === null. Say which one you would use in real code.
Next: Comments and code style.
Key points
- Convert on purpose with String(), Number() and Boolean() rather than relying on automatic conversion.
- The + operator joins text if either side is a string, while - * and / convert to numbers.
- The falsy values are false, 0, -0, 0n, an empty string, null, undefined and NaN. Everything else is truthy, including "0" and [].
- Loose equality == converts types and gives surprising results, so use === and !==.
- Objects and arrays are equal only when they are the very same object.