The Complete Guide to JavaScript Type Conversion

The Complete Guide to JavaScript Type Conversion

D
dongAuthor
8 min read

When working with JavaScript, you’ll encounter situations where "5" + 1 becomes "51", while "5" - 1 becomes 4. This may be confusing at first, but it’s due to JavaScript’s type conversion mechanism.

Type conversion refers to the process of converting one data type into another. Since JavaScript is a dynamically typed language, data types are determined and converted automatically at runtime, even without explicit type declarations by the developer. This feature can be convenient, but it can also lead to unexpected bugs.

This guide covers everything you need to know about type conversion in JavaScript, from the differences between explicit and implicit conversion to object conversion and common pitfalls to avoid in real-world applications. By understanding how type conversion works, you’ll be able to write safer and more predictable code.

Explicit vs Implicit Type Conversion

JavaScript type conversion falls into two broad categories.

Explicit Type Conversion is when the developer intentionally converts a value to another type using functions like String(), Number(), or Boolean().

Implicit Type Conversion (or Type Coercion) is when the JavaScript engine automatically converts a value’s type when it’s used in a context that expects a different type.

// Explicit conversion
const num = Number("123");  // String → Number

// Implicit conversion
const result = "5" + 1;     // "51" (Number 1 is coerced to string)

Explicit conversion improves readability and maintainability by clearly showing the developer’s intent. Implicit conversion can be convenient but may result in unexpected behavior.

Techniques for Explicit Type Conversion

Converting to String

There are three common ways to convert a value to a string.

Using String() Function

The String() function converts any value to a string.

String(123);        // "123"
String(true);       // "true"
String(null);       // "null"
String(undefined);  // "undefined"

Using .toString() Method

Most values have a .toString() method. However, null and undefined do not, so calling it on them throws an error.

(123).toString();     // "123"
true.toString();      // "true"
[1, 2, 3].toString(); // "1,2,3"

// null and undefined cause an error
// null.toString();  // TypeError

Concatenating with an Empty String

Adding an empty string ("") using + converts a value to a string.

123 + "";     // "123"
true + "";    // "true"
null + "";    // "null"

Converting to Number

There are multiple ways to convert a value to a number.

Using Number() Function

The Number() function converts strings or booleans to numbers. Non-numeric values return NaN (Not a Number).

Number("123");       // 123
Number("123abc");    // NaN
Number(true);        // 1
Number(false);       // 0
Number(null);        // 0
Number(undefined);   // NaN
Number("   123   "); // 123 (trims whitespace)

Using parseInt() and parseFloat()

parseInt() and parseFloat() parse a string from the beginning until an invalid character is encountered.

parseInt("123", 10);       // 123
parseInt("123px", 10);     // 123 (ignores "px")
parseInt("abc123", 10);    // NaN (doesn’t start with number)
parseFloat("3.14");        // 3.14
parseFloat("3.14.15");     // 3.14 (stops at first period)

The second argument of parseInt() specifies the radix (base). For decimal conversion, always specify 10.

Unary Plus Operator

The unary + operator quickly converts a value to a number.

+"123";     // 123
+"10";      // 10
+true;      // 1
+false;     // 0
+"abc";     // NaN

Converting to Boolean

Using Boolean() Function

The Boolean() function converts values to boolean.

Boolean(1);        // true
Boolean(0);        // false
Boolean("hello");  // true
Boolean("");       // false
Boolean([]);       // true (empty array is truthy)
Boolean({});       // true (empty object is truthy)

Falsy vs Truthy Values

JavaScript has specific values that evaluate to false, called falsy values.

Falsy values (8 total):

  • false
  • 0
  • -0
  • 0n (BigInt zero)
  • NaN
  • "" (empty string)
  • null
  • undefined

All other values are truthy. Surprisingly, the following values are truthy:

Boolean("false");      // true (non-empty string)
Boolean("0");          // true (non-empty string)
Boolean([]);           // true (empty array)
Boolean({});           // true (empty object)
Boolean(" ");          // true (whitespace string)
Boolean(function(){}); // true (functions are truthy)

Various Implicit Conversion Scenarios

String Context

In a + operation, if either operand is a string, the other will be converted to a string.

"5" + 1;         // "51"
1 + "5";         // "15"
"Hello" + true;  // "Hellotrue"
"Result: " + 100;// "Result: 100"

Order matters when multiple values are added:

1 + 2 + "3";    // "33" (1+2=3, then 3+"3"="33")
"1" + 2 + 3;    // "123" ("1"+2="12", "12"+3="123")

Number Context

All arithmetic operators except + convert operands to numbers.

"5" - 1;     // 4
"5" * "2";   // 10
"5" / 2;     // 2.5
"5" % 2;     // 1
"10" - "3";  // 7

When conversion fails, the result is NaN:

"abc" - 1;     // NaN
"5" * "abc";   // NaN

Boolean Context

In conditions (if, else), values are implicitly converted to boolean.

if ("") {
  console.log("Empty string"); // Not executed
}

if ("Hello") {
  console.log("Non-empty string"); // ✅ Executed
}

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

if ([]) {
  console.log("Array"); // ✅ Executed (empty array is truthy)
}

Logical operators (&&, ||, !) also operate in boolean contexts:

!!"hello";      // true
!!0;            // false
"text" && 5;    // 5 (returns second if first is truthy)
0 || "default"; // "default" (returns second if first is falsy)

Loose Equality (==)

The == operator performs implicit type conversion if types differ.

"5" == 5;          // true (string "5" becomes number 5)
"0" == false;      // true (both become 0)
0 == "";           // true (empty string becomes 0)
null == undefined; // true (special case)
null == 0;         // false (null doesn’t become 0)

Due to unexpected behavior, prefer the strict equality operator === instead.

"5" === 5;         // false
"0" === false;     // false
0 === "";          // false

Objects and Type Conversion

When converting objects to primitive values, JavaScript uses special methods.

toString() and valueOf() Methods

When converting objects to strings or numbers, JavaScript follows this order:

  1. String context: toString()valueOf()
  2. Number context: valueOf()toString()
const obj = {
  toString() {return "object";
  },
  valueOf() {return 42;
  }
};

String(obj);  // "object" (calls toString)
Number(obj);  // 42 (calls valueOf)
obj + "";     // "object" (string context)
obj - 0;      // 42 (number context)

Default conversion for arrays and objects:

String([1, 2, 3]); // "1,2,3"
String({});        // "[object Object]"
Number([]);        // 0 (empty array is 0)
Number([5]);       // 5 (single element)
Number([1, 2]);    // NaN (multiple elements)

JSON.stringify() and JSON.parse()

Use dedicated methods for converting to and from JSON.

// Object → JSON string
JSON.stringify({ a: 1, b: 2 }); // '{"a":1,"b":2}'

// JSON string → Object
JSON.parse('{"a":1,"b":2}');   // { a: 1, b: 2 }
Function Purpose
JSON.stringify() Object → JSON string
JSON.parse() JSON string → Object

Date Object Conversion

Date objects behave differently depending on the context.

const date = new Date("2025-10-22");

// Numeric conversion (timestamp)
Number(date);  // 1729544400000

// String conversion
String(date);  // "Wed Oct 22 2025 00:00:00 GMT+0"

Use this guide to confidently understand JavaScript type conversions and write cleaner, safer code.

The Complete Guide to JavaScript Type Conversion | devdong