JavaScript Type Conversion
Type conversion changes a value from one type to another on purpose. Converting early prevents surprises when values are combined.
Converting before adding
Number() turns the text into a real number, so the plus sign adds. Without conversion, the plus sign joins the values as text.
console.log(Number("42") + 8);
console.log("42" + 8);
console.log(typeof Number("42"));Automatic conversion
Most operators convert values on their own. The star converts the text to a number, but the plus keeps it as text.
console.log("5" * 3);
console.log("5" + 3);Converting to a boolean
An empty string converts to false. Any text with characters converts to true.
console.log(Boolean(""));
console.log(Boolean("hi"));Example
const empty = Number("");
const bad = String(Number("abc"));
const asText = String(42);
console.log(empty);
console.log(bad);
console.log(asText, typeof asText);Key points
- String(value) turns a value into a string.
- (42).toString() is the twin of String(42). Both return the string "42".
- Number() was first used in the Number Methods lesson to parse text. This lesson is the systematic pass over conversion.
- Boolean(value) turns a value into true or false.
- An empty string converts to the number 0.
In this example, an empty string converts to the number 0. Text with no digits converts to NaN, and the log shows it as text. String() turns the number 42 into text, and typeof confirms the new type.
Note
Text with no digits converts to NaN, the not-a-number value.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does "5" + 3 produce?