Skip to main content

Type Conversion and Coercion

Updated 5 min readMarkdown
Part of seriesDecode Javascript

Type conversion is the process of changing a value from one datatype to another.

  • Type Conversion: Explicitly converting a value to another datatype.
  • Type Coercion: JavaScript automatically converts a value to another datatype during an operation.

🔄 Type Conversion

JavaScript provides built-in functions to convert values into different datatypes.

🔤 Convert to String

Use String() or .toString() to convert a value into a string.

Example Result
String(123) "123"
String(true) "true"
String(null) "null"
String(undefined) "undefined"
String([1, 2, 3]) "1,2,3"
let age = 20;

console.log(String(age)); // "20"
console.log(age.toString()); // "20"

Note

null and undefined cannot directly use .toString() because they don't have that method.

🔢 Convert to Number

Use Number(), parseInt(), or parseFloat() to convert values into numbers.

Example Result
Number("123") 123
Number("12.5") 12.5
Number("") 0
Number("Hello") NaN
Number(true) 1
Number(false) 0
Number(null) 0
Number(undefined) NaN

parseInt() vs parseFloat() vs Number()

Number("123abc");    // NaN
parseInt("123abc");  // 123
parseFloat("12.5px"); // 12.5
parseInt("12.9");    // 12
parseFloat("12.9");  // 12.9
  • Number() converts the entire value. Invalid numeric strings produce NaN.
  • parseInt() extracts an integer from the beginning of a string.
  • parseFloat() extracts a floating-point number from the beginning of a string.

✅ Convert to Boolean

Use Boolean() to convert a value into true or false.

Boolean(1);         // true
Boolean(0);         // false
Boolean("Hello");   // true
Boolean("");        // false
Boolean(null);      // false
Boolean(undefined); // false
Boolean(NaN);       // false
Boolean([]);        // true
Boolean({});        // true

🚦 Truthy and Falsy Values

In JavaScript, every value is either truthy or falsy when evaluated in a Boolean context.

Falsy values:

Value Example
false Boolean(false)
0, -0 Boolean(0)
0n Boolean(0n)
"" Boolean("")
null Boolean(null)
undefined Boolean(undefined)
NaN Boolean(NaN)

All other values are truthy, including "0", "false", [], and {}.

if ("Hello") {
    console.log("Executed"); // Executed
}

if (0) {
    console.log("Not executed");
}

🤖 Type Coercion

Type coercion occurs when JavaScript automatically converts values to make an operation possible.

➕ The + Operator

The + operator performs either numeric addition or string concatenation.

Expression Result Explanation
5 + 2 7 Numeric addition
"5" + 2 "52" String concatenation
5 + "2" "52" String concatenation
true + 1 2 true converts to 1
false + 1 1 false converts to 0
null + 1 1 null converts to 0
undefined + 1 NaN undefined converts to NaN
[] + 1 "1" [] converts to ""
[1, 2] + 3 "1,23" Array converts to "1,2"

General rule:

  • If string concatenation is triggered, JavaScript converts the operands to primitives and then to strings as needed.
  • Otherwise, JavaScript converts the operands to primitives and performs numeric addition.
console.log("Age: " + 20); // "Age: 20"
console.log(10 + 20);      // 30
console.log(true + true); // 2
console.log([] + []);      // ""

➖ Other Arithmetic Operators

Operators such as -, *, /, and % generally convert operands to numbers.

Expression Result
"5" - 2 3
"5" * 2 10
"10" / 2 5
"5" % 2 1
"Hello" - 2 NaN
console.log("10" - 5); // 5
console.log("10" * 2); // 20
console.log("10" / 2); // 5

⚖️ Comparison Coercion

The == operator allows type coercion, whereas === compares without converting the operand types.

Expression Result
5 == "5" true
5 === "5" false
0 == false true
0 === false false
null == undefined true
null === undefined false
"" == 0 true
"" === 0 false

Note

Prefer === and !== unless you specifically need the coercion behavior of loose equality.

🧠 Logical Operator Coercion

Logical operators such as && and || evaluate truthiness but return one of their operand values, not necessarily a Boolean.

Expression Result
"Hello" && 5 5
0 && 5 0
`""
`0
!0 true
!"Hello" false
  • && returns the first falsy operand, or the last operand if all are truthy.
  • || returns the first truthy operand, or the last operand if all are falsy.
  • ! converts the operand to a Boolean and negates it.

⚠️ Special Cases

typeof and NaN

typeof NaN; // "number"
typeof null; // "object"

NaN means "Not a Number", but its datatype is still number. The result of typeof null is a historical JavaScript behavior.

Checking for NaN

console.log(NaN === NaN);       // false
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("Hi")); // false

Use Number.isNaN() to check whether a value is actually NaN.

Implicit Conversion in Conditions

let age = "18";

if (age >= 18) {
    console.log("Eligible"); // Eligible
}

The comparison converts "18" to a number before comparing it with 18.

2 views

No comments yet. Be the first to comment.

Decode Javascript

Part 5 of 9

Explore JavaScript one concept at a time, from the fundamentals to advanced topics. Learn through clear explanations, practical examples, and code as we uncover how JavaScript works and use it to build for the web.

Up nextStringsA String is a sequence of characters used to store text data. let name = "Rohan"; let city = "Bangalore"; Strings can be enclosed in "", '' or `` 👶 Creating strings For creating a string, new String