Clean β’ Professional
Type conversion in JavaScript means converting a value from one data type to another.
It can happen automatically (implicit) or manually (explicit).
JavaScript automatically converts types in certain operations like arithmetic, comparison, or string concatenation.
Examples:
// String + Number β String (concatenation)
console.log("5" + 3); // "53"
// Number - String β Number (if string is numeric)
console.log("5" - 3); // 2
// Boolean in arithmetic
console.log(true + 1); // 2 (true β 1)
console.log(false * 5); // 0 (false β 0)
// Loose equality (==) triggers type coercion
console.log(5 == "5"); // true ("5" β 5)
console.log(true == 1); // true (true β 1)
You can manually convert types using built-in functions or operators.
Using String()
console.log(String(123)); // "123"
console.log(String(true)); // "true"
console.log(String(null)); // "null"
Using .toString()
let num = 123;
console.log(num.toString()); // "123"
console.log([1, 2, 3].toString()); // "1,2,3"
Using concatenation with an empty string
console.log("" + 123); // "123"
Using Number()
console.log(Number("123")); // 123
console.log(Number("12.34")); // 12.34
console.log(Number("abc")); // NaN
console.log(Number(true)); // 1
console.log(Number(null)); // 0
Using the unary + operator
console.log(+"123"); // 123
console.log(+"abc"); // NaN
Using parseInt() and parseFloat()
console.log(parseInt("123px")); // 123
console.log(parseFloat("12.34px")); // 12.34
Using Boolean()
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hello"));// true
console.log(Boolean(null)); // false
Using double negation !!
console.log(!!1); // true
console.log(!!0); // false
console.log(!!""); // false
JavaScript considers certain values as "falsy" (convert to false in a boolean context):
false, 0, -0, 0n, "", null, undefined, NaN
All other values are truthy.
console.log(!!"0"); // true (string "0" is truthy)
console.log(!![]); // true (arrays are truthy)
Form input handling: Convert string inputs to numbers for calculations.
let input = "42";
let result = Number(input) * 2; // 84
Conditional checks: Convert values to booleans for logic.
let value = "hello";
if (Boolean(value)) {
console.log("Truthy value"); // Prints
}
String formatting: Convert numbers or booleans to strings for display.
let score = 100;
console.log("Score: " + String(score)); // "Score: 100"
NaN and Invalid Conversions: Converting non-numeric strings to numbers results in NaN.
console.log(Number("abc")); // NaN
Precision Issues: Be cautious with floating-point numbers
console.log(0.1 + 0.2); // 0.30000000000000004
Type coercion pitfalls
Use typeof to verify types before converting:
let value = "123";
if (typeof value === "string") {
let num = Number(value);
console.log(num + 10); // 133
}Β