Type Conversion in JavaScript
- To String
String(): Converts a value to a string.let num = 42;let str = String(num); // "42"console.log(typeof str); // "string"javascripttoString(): A method available on most objects (exceptnullandundefined).let num = 42;let str = num.toString(); // "42"javascript
- To Number
Number(): Converts a value to a number.let str = "123";let num = Number(str); // 123console.log(typeof num); // "number"// Non-numeric strings result in NaNconsole.log(Number("hello")); // NaNjavascriptparseInt(): Parses a string and returns an integer.let str = "123.45";let int = parseInt(str); // 123console.log(parseInt("123px")); // 123javascriptparseFloat(): Parses a string and returns a floating-point number.let str = "123.45";let float = parseFloat(str); // 123.45console.log(parseFloat("12.34px")); // 12.34javascript
- To Boolean
Boolean(): Converts a value to a boolean.console.log(Boolean(0)); // falseconsole.log(Boolean(1)); // trueconsole.log(Boolean("")); // falseconsole.log(Boolean("hello")); // truejavascript
- String Concatenation with
+- When one operand is a string, the other is coerced to a string.
let num = 5;let str = "The number is " + num; // "The number is 5"console.log(typeof str); // "string"javascript
- When one operand is a string, the other is coerced to a string.
- Arithmetic Operations (Except
+)- Operands (
-,*,/,%) are coerced to numbers.let str = "10";let result = str - 5; // 5 (string "10" coerced to number 10)console.log(typeof result); // "number"javascript
- Operands (
- Equality Operator (
==)- The loose equality operator performs type coercion before comparison.
console.log(5 == "5"); // true (string "5" coerced to number 5)console.log(false == 0); // true (false coerced to 0)console.log(null == undefined); // true (special case)javascript
- The loose equality operator performs type coercion before comparison.
- Strict Equality Operator (
===)- No coercion occurs; both type and value must match.
console.log(5 === "5"); // false (different types)console.log(false === 0); // falsejavascript
- No coercion occurs; both type and value must match.
- Boolean Coercion in Conditionals
- Non-boolean values are coerced to
trueorfalsein logical contexts.if ("hello") {console.log("Truthy"); // Executes (non-empty string is true)}if (0) {console.log("Falsy"); // Skipped (0 is false)}javascript
- Non-boolean values are coerced to
JavaScript follows specific rules when coercing types:
- String + Anything: Results in string concatenation.
- Number and String in
-,*,/,%: String is coerced to a number. - Objects: Converted to primitives via
toString()orvalueOf()methods.let obj = { valueOf: () => 42 };console.log(obj + 1); // 43javascript
+: Attempts to convert its operand to a number.console.log(+"123"); // 123console.log(+"abc"); // NaNjavascript-: Converts to a number and negates it.console.log(-"123"); // -123javascript
- Use Explicit Conversion When Possible: Avoid relying on coercion for critical logic to reduce bugs.
let str = "42";let num = Number(str); // Explicit, predictablejavascript
- Use
===Over==: Strict equality avoids unexpected coercion. - Understand Context: Know when coercion occurs (e.g.,
ifstatements, arithmetic). - Test Edge Cases: Values like
null,undefined, andNaNcan behave unexpectedly.
console.log("2" + 2); // "22" (string concatenation)console.log("2" * 2); // 4 (string coerced to number)javascript
console.log([] + []); // "" (empty arrays coerce to empty strings)console.log([] + {}); // "[object Object]" (array to "", object to string)javascript
let result = Number("abc"); // NaNconsole.log(result === NaN); // false (NaN is not equal to itself)console.log(isNaN(result)); // true (use this instead)javascript
| Operation/Type | String | Number | Boolean |
|---|---|---|---|
String() | Same | e.g., "42" | e.g., "true" |
Number() | e.g., 123 or NaN | Same | 1 or 0 |
Boolean() | true (if non-empty) | true (if not 0) | Same |
+ (with string) | Concatenation | Concatenation | Concatenation |
-, *, / | Coerces to number | Number operation | Coerces to number |