JavaScript Type Conversion and Coercion: Explicit vs Implicit with Examples
Values often arrive as the wrong type. Text from a web page, a form field, a CSV file or a command-line argument is always a string, even when it looks like a number. JavaScript can convert types for you (coercion), but its automatic rules are a famous source of bugs such as "5" + 2 giving "52". In this lesson you will learn to convert values explicitly and safely, understand the implicit rules, and parse real UI text like "₹1,299.50" into numbers you can assert on.
📖 What You’ll Learn: explicit conversion with String(), Number(), Boolean(), parseInt() and parseFloat(), the unary plus, toString() and toFixed(), implicit coercion with +, -, * and comparisons, how null, undefined, empty strings and arrays convert, NaN and Number.isNaN, and parsing numbers and dates from text.
🔄 Conversion vs Coercion
Definition: type conversion means turning a value of one type into another type. When you do it on purpose with a function such as Number("42"), it is explicit conversion. When JavaScript does it automatically because an operator needs a different type, it is implicit conversion, also called type coercion.
📄 intro.js
const fromInput = "42"; // text from a form, a page or process.argv
const explicit = Number(fromInput); // you decide: string -> number
const implicit = fromInput * 2; // JavaScript decides: * needs numbers
console.log(explicit, typeof explicit);
console.log(implicit, typeof implicit);
console.log(fromInput + 2); // + with a string joins text instead!
⌨️ Terminal
node intro.js
🖥️ Output
42 number
84 number
422
Values can be converted to only three primitive types: string, number and boolean. Learn the rules for those three and coercion stops being surprising.
🔤 Convert to String
📄 to-string.js
console.log(String(123)); // "123"
console.log(String(true)); // "true"
console.log(String(null)); // "null"
console.log(String(undefined)); // "undefined"
console.log(String([1, 2, 3])); // "1,2,3"
console.log(String({ a: 1 })); // "[object Object]"
const price = 7.5;
console.log(price.toString(), price.toFixed(2)); // toFixed rounds and returns a string
console.log((255).toString(16)); // to hexadecimal
console.log(`${42}`, 42 + ""); // template literal and + "" also convert
⌨️ Terminal
node to-string.js
🖥️ Output
123
true
null
undefined
1,2,3
[object Object]
7.5 7.50
ff
42 42
String(value)works for every value, includingnullandundefined.value.toString()throws onnullandundefinedbecause they have no methods.- Plain objects become
"[object Object]". UseJSON.stringify(obj)to turn an object into readable text.
🔢 Convert to Number: Number(), parseInt(), parseFloat()
Number(value) converts the whole value or returns NaN if any part is invalid. parseInt() and parseFloat() read a number from the start of a string and stop at the first invalid character.
📄 to-number.js
console.log(Number("42"), Number("3.14"), Number(" 12 "));
console.log(Number(""), Number("12px"), Number("abc"));
console.log(Number(true), Number(false), Number(null), Number(undefined));
console.log(Number([]), Number([7]), Number([1, 2]));
console.log(parseInt("12px"), parseFloat("3.75rem"), parseInt("3.99"));
console.log(parseInt("px12"), parseInt("101", 2), parseInt("ff", 16));
console.log(+"8", +"", +"8.5kg"); // unary plus works like Number()
⌨️ Terminal
node to-number.js
🖥️ Output
42 3.14 12
0 NaN NaN
1 0 0 NaN
0 7 NaN
12 3.75 3
NaN 5 255
8 0 NaN
| Input | Number() | parseInt() | parseFloat() |
|---|---|---|---|
"42" | 42 | 42 | 42 |
"3.99" | 3.99 | 3 | 3.99 |
"12px" | NaN | 12 | 12 |
"" | 0 | NaN | NaN |
null | 0 | NaN | NaN |
true | 1 | NaN | NaN |
⚠️ Watch out: Number("") and Number(null) return 0, not NaN. An empty form field can therefore silently become the number 0. Check for empty strings before converting user input.
💡 Tip: Always pass the radix (base) to parseInt: parseInt(value, 10). It documents your intent and avoids surprises with strings such as "0x1A", which parseInt reads as hexadecimal.
✅ Convert to Boolean
Boolean(value) (or !!value) converts using a short list of falsy values. Everything not on the list is truthy.
📄 to-boolean.js
const values = [
["0", 0], ["-0", -0], ["0n", 0n], ["\"\"", ""], ["null", null], ["undefined", undefined],
["NaN", NaN], ["false", false], ["\"0\"", "0"], ["\"false\"", "false"], ["\" \"", " "],
["[]", []], ["{}", {}], ["-1", -1],
];
for (const [label, value] of values) {
console.log(label.padEnd(10), "->", Boolean(value));
}
⌨️ Terminal
node to-boolean.js
🖥️ Output
0 -> false
-0 -> false
0n -> false
"" -> false
null -> false
undefined -> false
NaN -> false
false -> false
"0" -> true
"false" -> true
" " -> true
[] -> true
{} -> true
-1 -> true
The falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Note that the strings "0" and "false", empty arrays and empty objects are all truthy. The next lessons use this in conditions.
⚠️ Implicit Coercion with Operators
Operators coerce their operands. The rules that matter most:
+: if either side is a string, both are converted to strings and joined. Otherwise both become numbers.-,*,/,%,**: always convert both sides to numbers.- Comparisons
<>: convert to numbers, unless both sides are strings, which are compared alphabetically. - Conditions (
if,&&,||,!): convert to boolean.
📄 coercion.js
console.log("5" + 2); // string + number -> "52"
console.log(5 + 2 + "1"); // left to right: 7 + "1" -> "71"
console.log("1" + 5 + 2); // "15" + 2 -> "152"
console.log("5" - 2); // - always uses numbers -> 3
console.log("6" * "2"); // 12
console.log("10" / "4"); // 2.5
console.log(true + 1); // true -> 1
console.log(null + 1); // null -> 0
console.log(undefined + 1); // undefined -> NaN
console.log([] + []); // both become "" -> ""
console.log([1, 2] + [3]); // "1,2" + "3"
console.log("10" > "9"); // both strings: compared alphabetically -> false
console.log("10" > 9); // one number: numeric comparison -> true
⌨️ Terminal
node coercion.js
🖥️ Output
52
71
152
3
12
2.5
2
1
NaN
1,23
false
true
⚠️ Watch out: Sorting or comparing numbers that are stored as strings gives alphabetical results: "10" < "9" because "1" comes before "9". Convert to numbers before comparing prices, counts or IDs read from a page.
🚫 NaN: Not a Number
Definition: NaN is a special number value that means “the result is not a valid number”. It appears when a conversion or calculation fails. NaN is the only value that is not equal to itself, so value === NaN never works.
📄 nan.js
const qty = Number("two");
console.log(qty, typeof qty);
console.log(qty === NaN); // always false!
console.log(Number.isNaN(qty)); // correct check
console.log(isNaN("hello")); // global isNaN converts first -> true
console.log(Number.isNaN("hello")); // only true for the NaN value itself -> false
console.log(Number.isFinite(Number("1e3")), Number.isFinite(Infinity));
⌨️ Terminal
node nan.js
🖥️ Output
NaN number
false
true
true
false
true false
💡 Tip: To validate that text is a usable number, convert it and check Number.isFinite(n). It rejects NaN, Infinity and -Infinity in one call.
🧪 Tester Scenario: Parse Prices and Counts from UI Text
A page shows "₹1,299.50", "Showing 25 of 1,024 results" or "$0.99". To assert on these values, remove everything except digits, the decimal point and the minus sign, then convert:
📄 parse-ui.js
function parsePrice(text) {
const cleaned = text.replace(/[^0-9.-]/g, ""); // keep digits, dot and minus
if (cleaned === "") throw new Error(`No number in "${text}"`);
const value = Number(cleaned);
if (!Number.isFinite(value)) throw new Error(`Invalid price "${text}"`);
return value;
}
const cartLines = ["₹1,299.50", "₹ 450.00", "₹50"];
const total = cartLines.map(parsePrice).reduce((sum, p) => sum + p, 0);
console.log("Line prices:", cartLines.map(parsePrice));
console.log("Total:", total.toFixed(2));
const summary = "Showing 25 of 1,024 results";
const [shown, all] = summary.match(/[\d,]+/g).map((s) => parseInt(s.replace(/,/g, ""), 10));
console.log({ shown, all });
⌨️ Terminal
node parse-ui.js
🖥️ Output
Line prices: [ 1299.5, 450, 50 ]
Total: 1799.50
{ shown: 25, all: 1024 }
replace(/[^0-9.-]/g, "")uses a regular expression to delete currency symbols, commas and spaces (Module 5 explains regular expressions).- The function throws a clear error for text without a number, so a broken page fails the test instead of comparing
NaN. match(/[\d,]+/g)finds every group of digits and commas in the sentence.
⚠️ Watch out: This simple cleaner assumes “.” is the decimal separator. Pages in locales that write 1.299,50 need a locale-aware parser or a fixed test locale (Playwright’s locale option).
📅 Bonus: Dates and JSON Conversion
Two more conversions you will use all the time in tests:
📄 dates-json.js
// Dates <-> numbers and strings
const d = new Date("2026-11-23T10:30:00Z");
console.log(d.getTime()); // milliseconds since 1 Jan 1970 (UTC)
console.log(d.toISOString()); // standard string for APIs
console.log(new Date(0).toISOString());
// Objects <-> JSON text
const payload = { id: 7, tags: ["smoke"], active: true };
const text = JSON.stringify(payload);
console.log(text, typeof text);
const back = JSON.parse(text);
console.log(back.tags[0], typeof back);
⌨️ Terminal
node dates-json.js
🖥️ Output
1795429800000
2026-11-23T10:30:00.000Z
1970-01-01T00:00:00.000Z
{"id":7,"tags":["smoke"],"active":true} string
smoke object
API responses arrive as JSON text and are converted with JSON.parse (Playwright’s response.json() does this for you). The JSON lesson in Module 7 goes further.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Convert "19.99", "5" and "0.01" to numbers and print their sum with two decimals.
Show answer
📄 practice1.js
const prices = ["19.99", "5", "0.01"];
const sum = prices.map(Number).reduce((a, b) => a + b, 0);
console.log(sum.toFixed(2));🖥️ Output
25.00Q2. Predict each result before running: "3" + 4 + 5, 3 + 4 + "5", "3" * "4", "10" - "4" + "1".
Show answer
📄 practice2.js
console.log("3" + 4 + 5);
console.log(3 + 4 + "5");
console.log("3" * "4");
console.log("10" - "4" + "1");🖥️ Output
345
75
12
61Evaluation goes left to right. "3" + 4 is already a string, so 5 is appended. 3 + 4 is 7 before meeting the string. "10" - "4" is the number 6, then + "1" joins text.
Q3. Write toQuantity(text) that returns a whole number from input such as " 3 ", and throws an error for "", "abc" or "2.5".
Show answer
📄 practice3.js
function toQuantity(text) {
const trimmed = String(text).trim();
const n = Number(trimmed);
if (trimmed === "" || !Number.isInteger(n)) {
throw new Error(`Invalid quantity: "${text}"`);
}
return n;
}
console.log(toQuantity(" 3 "));
for (const bad of ["", "abc", "2.5"]) {
try {
toQuantity(bad);
} catch (e) {
console.log(e.message);
}
}🖥️ Output
3
Invalid quantity: ""
Invalid quantity: "abc"
Invalid quantity: "2.5"The empty-string check is needed because Number("") is 0, a valid integer.
Q4. An array of order IDs read from a table is ["10", "9", "100", "25"]. Sort it numerically from smallest to largest.
Show answer
📄 practice4.js
const ids = ["10", "9", "100", "25"];
console.log([...ids].sort()); // alphabetical: wrong
console.log(ids.map(Number).sort((a, b) => a - b)); // numeric: right🖥️ Output
[ '10', '100', '25', '9' ]
[ 9, 10, 25, 100 ]Q5. Print the boolean value of "0", 0, "false", [] and "" using !!.
Show answer
📄 practice5.js
for (const v of ["0", 0, "false", [], ""]) {
console.log(JSON.stringify(v), !!v);
}🖥️ Output
"0" true
0 false
"false" true
[] true
"" falseQ6. Extract the rating number from "Rated 4.5 out of 5 (1,203 reviews)" as a number, and the review count as a whole number.
Show answer
📄 practice6.js
const text = "Rated 4.5 out of 5 (1,203 reviews)";
const rating = parseFloat(text.match(/[\d.]+/)[0]);
const reviews = parseInt(text.match(/\(([\d,]+)/)[1].replace(/,/g, ""), 10);
console.log(rating, reviews, typeof rating, typeof reviews);🖥️ Output
4.5 1203 number number🧠 MCQ Quiz: Type Conversion and Coercion
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What is
"5" + 2?Answer:"52". With + and a string operand, both sides are joined as strings. - What is
"5" - 2?Answer:3. The minus operator always converts both sides to numbers. - What does
Number("")return?Answer:0. An empty (or whitespace-only) string converts to 0, a common bug with empty inputs. - What does
parseInt("12px", 10)return?Answer:12. parseInt reads digits from the start and stops at “p”.Number("12px")would be NaN. - Which check correctly detects NaN?Answer:
Number.isNaN(x). NaN is not equal to anything, including itself. - Which of these is truthy?Answer:
"0". Any non-empty string is truthy, even “0” and “false”. - What is
"10" > "9"?Answer:false. Two strings are compared character by character, and “1” comes before “9”. - What does
(7.456).toFixed(2)return?Answer: The string"7.46". toFixed rounds and returns a string; wrap it in Number() if you need a number. - What is
null + 1?Answer:1. null converts to 0 in arithmetic; undefined converts to NaN. - Why should you pass 10 as the second argument to parseInt?Answer: It states the base explicitly and avoids reading strings like “0x1A” as hexadecimal. The radix tells parseInt which number base to use.
💼 Interview Questions and Answers
Q1. What is the difference between type conversion and type coercion?
Conversion is explicit: you call Number(), String(), Boolean(), parseInt() and so on. Coercion is implicit: the engine converts automatically because an operator or context needs another type, for example "5" * 2, if (value) or "a" + 1. Coercion only ever produces strings, numbers or booleans.
Q2. What is the difference between Number(), parseInt() and parseFloat()?
Number() converts the entire value and returns NaN if anything is invalid (Number("12px") is NaN), and treats "", null and false as 0. parseInt(str, radix) parses an integer from the beginning of a string and stops at the first invalid character. parseFloat() does the same but keeps decimals. Use Number() for strict validation and the parse functions for strings with units.
Q3. Explain the output of these expressions.
📄 tricky.js
console.log([] + {});
console.log(1 + "2" - 1);
console.log(true + true);
console.log("b" + "a" + +"a" + "a");
⌨️ Terminal
node tricky.js
🖥️ Output
[object Object]
11
2
baNaNa
[] + {}: both convert to strings,""and"[object Object]".1 + "2"is"12", then- 1converts back to a number: 11.true + true: booleans become 1 + 1 = 2.+"a"isNaN, which is joined as text, giving"baNaNa".
Q4. How do you safely read a number from text on a web page in a test?
- Get the text (for example
await locator.textContent()) and trim it. - Remove formatting such as currency symbols, thousands separators and units with a regular expression.
- Convert with
Number()and validate withNumber.isFinite(); throw a clear error if it fails. - Compare with a tolerance for decimals, or compare integer cents, to avoid floating-point issues.
- Fix the test locale so number formatting is predictable.
Q5. Why is isNaN() considered unreliable?
The global isNaN(x) first converts x to a number, so isNaN("hello") is true even though "hello" is a string, not the NaN value. Number.isNaN(x) does not convert and returns true only for NaN itself. For input validation, Number.isFinite(Number(x)) is usually what you want.
❓ Frequently Asked Questions
🤔 How do I convert a string to a number in JavaScript?
Use Number(str) when the whole string must be a number, or parseInt(str, 10) / parseFloat(str) when it starts with a number followed by other text, such as "12px". Check the result with Number.isFinite().
🤔 How do I convert a number to a string?
Use String(n), n.toString() or a template literal `${n}`. Use n.toFixed(2) for a fixed number of decimal places.
🤔 Why does “1” + 1 equal “11”?
When either side of + is a string, JavaScript converts the other side to a string and joins them. Convert the string first: Number("1") + 1 is 2.
🤔 Is it bad to rely on type coercion?
Coercion in conditions (if (items.length)) is normal and readable. Coercion in arithmetic and equality (==) causes bugs, so convert explicitly and use ===.
🏁 Summary
- Explicit conversion:
String(),Number(),Boolean(),parseInt(s, 10),parseFloat(),toFixed(). +joins strings if either side is a string;-,*,/always convert to numbers.Number("")andNumber(null)are 0;Number(undefined)and invalid text areNaN.- Check numbers with
Number.isNaN()orNumber.isFinite(), never with=== NaN. - Text from pages, files and arguments is always a string: clean it and convert it before comparing.
Next, continue with Lesson 9: Numbers, Math and BigInt. For extra practice, solve the JavaScript type conversion practice programs.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in