JavaScript Notes
Master JavaScript type conversion and coercion: String(), Number(), Boolean(), parseInt, parseFloat, implicit coercion rules, and truthy/falsy values with examples.
JavaScript is a dynamically typed language — a variable can hold any type, and sometimes JavaScript will automatically convert between types. This behavior is called type coercion, and it can be one of the most confusing parts of JavaScript for beginners. Master this and you'll understand why "5" + 3 === "53" but "5" - 3 === 2.
Real World Analogy
Imagine you're at a currency exchange counter:
- Explicit conversion = you hand dollars to the cashier and ask to convert them to rupees. You *intentionally* triggered the conversion.
- Implicit conversion = a shop in India accepts your dollar bill and automatically gives you change in rupees. The conversion happened *automatically* without you requesting it.
Both result in a different currency (type), but one is deliberate and one is automatic.
Part 1: Explicit Type Conversion
Converting TO String
42 3.14 true false null undefined 1,2,3 255 ff 11111111 Age: 25 string
Converting TO Number
42 3.14 0 0 NaN 1 0 0 NaN 5 NaN
// parseInt() — parses integer from string (stops at first non-digit)
console.log(parseInt("42px")); // 42 (ignores "px")
console.log(parseInt("3.99")); // 3 (truncates decimal)
console.log(parseInt("abc")); // NaN
console.log(parseInt("0xFF", 16)); // 255 (hex to decimal)
// parseFloat() — parses floating point number
console.log(parseFloat("3.14em")); // 3.14 (ignores "em")
console.log(parseFloat("12.5.6")); // 12.5 (stops at second dot)42 3 NaN 255 3.14 12.5
Converting TO Boolean
// Boolean() — explicit boolean conversion
// FALSY values → false (there are only 6):
console.log(Boolean(false)); // false
console.log(Boolean(0)); // false
console.log(Boolean(-0)); // false
console.log(Boolean(0n)); // false (BigInt zero)
console.log(Boolean("")); // false (empty string)
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
// TRUTHY values → true (everything else):
console.log(Boolean(1)); // true
console.log(Boolean("hello")); // true
console.log(Boolean(" ")); // true (space is truthy!)
console.log(Boolean([])); // true (empty array is truthy!)
console.log(Boolean({})); // true (empty object is truthy!)
console.log(Boolean(-1)); // true (negative numbers too)false false false false false false false false true true true true true true
The 6 Falsy Values — Memorize These!
Part 2: Implicit Type Coercion
This is where JavaScript surprises beginners. Coercion happens automatically during operations.
The + Operator — Addition vs Concatenation
53 35 5 true null undefined 1,2 8 33 123
-, *, / Operators — Always Numeric
// Math operators (except +) always try to convert to number
console.log("10" - 3); // 7 ("10" → 10)
console.log("10" * 2); // 20
console.log("10" / 2); // 5
console.log("abc" - 1); // NaN
console.log(true - false); // 1 (true=1, false=0)
console.log(null - 1); // -1 (null → 0)7 20 5 NaN 1 -1
Coercion in Comparisons ==
This is why experts recommend always using ===:
// Loose equality (==) coerces types
console.log(1 == "1"); // true (string "1" → number 1)
console.log(0 == false); // true (false → 0)
console.log(0 == ""); // true (both → 0)
console.log(null == undefined); // true (special rule)
console.log(null == 0); // false (special — null only == undefined)
console.log(NaN == NaN); // false (NaN is never equal to anything!)
// Strict equality (===) — NO coercion
console.log(1 === "1"); // false (different types)
console.log(0 === false); // falsetrue true true true false false false false
Coercion in if Conditions (Boolean Context)
0 → falsy
1 → TRUTHY
"" → falsy
"hello" → TRUTHY
null → falsy
undefined → falsy (shown as undefined in actual output)
[] → TRUTHY
{} → TRUTHY
null → falsy (NaN shown as null in JSON)Conversion Table: The Rules
Common Mistakes
❌ Mistake 1: Using + to add a number to user input
// ❌ WRONG — prompt returns a string!
const a = prompt("Enter a number:"); // "10"
const b = prompt("Enter another:"); // "5"
const result = a + b;
console.log(result); // "105" — concatenation, not addition!// ✅ CORRECT — convert first
const a = Number(prompt("Enter a number:")); // 10
const b = Number(prompt("Enter another:")); // 5
const result = a + b;
console.log(result); // 15❌ Mistake 2: Trusting that empty array is falsy
// ❌ WRONG — [] is TRUTHY, not falsy!
const cart = [];
if (cart) {
console.log("Cart has items"); // This RUNS even with empty cart!
}// ✅ CORRECT — check the length
if (cart.length > 0) {
console.log("Cart has items");
} else {
console.log("Cart is empty");
}❌ Mistake 3: Using == with different types
// ❌ CONFUSING — leads to bugs
console.log(0 == "0"); // true
console.log(0 == []); // true
console.log("0" == []); // false (but above two are true — inconsistent!)// ✅ CORRECT — always use === for predictable comparisons
console.log(0 === "0"); // false
console.log(0 === []); // false
console.log("0" === []); // false❌ Mistake 4: Checking for empty string incorrectly
// ❌ WRONG — space string " " is TRUTHY
const input = " "; // user typed a space
if (input) {
console.log("Input provided"); // RUNS — but it's just a space!
}// ✅ CORRECT — trim the input first
const input = " ";
if (input.trim()) {
console.log("Real input provided");
} else {
console.log("Empty or whitespace only");
}Key Takeaways
- Explicit conversion uses functions:
String(),Number(),Boolean(),parseInt(),parseFloat() - Implicit coercion happens automatically — mostly during
+, comparison, andifconditions - The
+operator prefers string concatenation if either operand is a string -,*,/always coerce operands to numbers- There are 8 falsy values:
false,0,-0,0n,"",null,undefined,NaN - Empty array
[]and empty object{}are TRUTHY — this surprises many beginners Number(null)=0,Number(undefined)=NaN,Number("")=0- Always use
===for comparisons to avoid coercion surprises - Always
Number()orparseInt()user input before arithmetic
Interview Questions & Answers
Q1. What is the difference between type conversion and type coercion in JavaScript?
Answer: Both change a value's type, but who initiates them differs:
- Type conversion (explicit): the developer explicitly calls a conversion function like
Number("5"),String(42), orBoolean(0). - Type coercion (implicit): JavaScript automatically converts types when operators or contexts expect a specific type, like
"5" - 3(coerces "5" to 5) orif (value)(coerces value to boolean).
Q2. What does Number("") return? What about Number(null) and Number(undefined)?
Answer:
Number("")→0(empty string becomes zero — surprises many!)Number(null)→0(null becomes zero)Number(undefined)→NaN(undefined cannot be represented numerically)
These differences are critical when processing form input or API data.
Q3. Why does "5" + 3 equal "53" but "5" - 3 equals 2?
Answer: The + operator serves double duty — it's addition AND string concatenation. When either operand is a string, + converts the other to a string and concatenates. All other arithmetic operators (-, *, /, %) only do math, so they always convert both operands to numbers first.
Q4. What are the falsy values in JavaScript?
Answer: There are 8 falsy values — values that convert to false in a boolean context: false, 0, -0, 0n (BigInt zero), "" (empty string), null, undefined, NaN Everything else is truthy, including "0", "false", [], {}, -1, and Infinity.
Q5. Why is an empty array [] truthy in JavaScript?
Answer: Because [] is an object (arrays are objects), and all objects (regardless of content) are truthy in JavaScript. Only the 8 specific falsy values convert to false. To check if an array is empty, use array.length === 0, not a simple truthiness check.
Q6. What is the difference between parseInt() and Number() for string-to-number conversion?
Answer:
Number("42px")→NaN(strict — fails if any non-numeric character present)parseInt("42px")→42(lenient — reads integer until it hits a non-digit)
Use Number() when you expect a clean numeric string. Use parseInt() or parseFloat() when parsing values with units (like CSS values "16px", "1.5em").
Q7. What happens with NaN == NaN?
Answer: NaN === NaN is false — NaN is the only value in JavaScript that is not equal to itself. This is defined by the IEEE 754 floating-point standard. To check for NaN, use Number.isNaN(value) (preferred) or isNaN(value) (coerces first, less precise).
Q8. How does JavaScript coerce values in loose equality == comparisons?
Answer: The ECMAScript spec defines a specific set of coercion rules for ==:
- If same type, compare directly
null == undefined→true(only these two are loosely equal to each other)- If one is number and other is string, convert string to number
- If one is boolean, convert to number (true→1, false→0)
- If one is object and other is primitive, call
valueOf()/toString()on the object
This complexity is why === is strongly recommended in modern JavaScript.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Type Conversion Complete Guide – Explicit & Implicit Coercion with Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, basics, type, conversion
Related JavaScript Master Course Topics