JavaScript

JavaScript Type Conversion: Complete Guide with Examples

9 min read Harshit No comments
Complete Guide with Examples

JavaScript type conversion is the process of converting a value from one data type to another. For example, you can convert a string into a number, a number into a string, or a value into a Boolean.

Understanding type conversion is important because JavaScript sometimes converts values automatically. If you do not understand how this works, you may get unexpected results in calculations, comparisons, and form handling.

In this tutorial, you will learn about implicit conversion, explicit conversion, type coercion, and common type conversion methods in JavaScript, with practical examples.

What Is Type Conversion in JavaScript?

Type conversion means changing a value from one data type to another.

For example:

let value = "100";

let number = Number(value);

console.log(number);
console.log(typeof number);

Output:

100
number

In this example, the Number() function converts the string "100" into the number 100.

JavaScript supports two main types of conversion:

  1. Explicit Type Conversion: The developer manually converts a value.
  2. Implicit Type Conversion: JavaScript automatically converts a value when an operation requires it.

Let’s understand both types.

1. Explicit Type Conversion

Explicit type conversion happens when you intentionally convert a value using a function or method.

JavaScript provides several conversion functions, including:

  • Number()
  • String()
  • Boolean()
  • parseInt()
  • parseFloat()

Convert a String to a Number

You can use the Number() function to convert a string into a number.

let price = "500";

let result = Number(price);

console.log(result);
console.log(typeof result);

Output:

500
number

This is useful when processing numeric values received from HTML form inputs or APIs.

For example, input fields usually provide their values as strings, even when the user enters a number.

let price = "200";
let quantity = "3";

let total = Number(price) * Number(quantity);

console.log(total);

Output:

600

Important: If you perform arithmetic directly on numeric strings using +, JavaScript may concatenate them instead of adding them.

let a = "10";
let b = "20";

console.log(a + b);

Output:

1020

Convert the strings to numbers when you intend to perform numeric addition.

What Happens When a String Cannot Be Converted?

If a string does not represent a valid number, Number() returns NaN (Not a Number).

let value = "Hello";

console.log(Number(value));

Output:

NaN

You can check for this result using Number.isNaN().

let value = Number("Hello");

console.log(Number.isNaN(value));

Output:

true

Convert a Number to a String

Use String() to convert a number into a string.

let age = 25;

let result = String(age);

console.log(result);
console.log(typeof result);

Output:

25
string

You can also use the toString() method on a number.

let price = 100;

console.log(price.toString());

Output:

100

However, String() can also convert null and undefined into strings, while calling .toString() directly on either value causes an error.

Convert a Value to Boolean

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

console.log(Boolean(1));
console.log(Boolean(0));
console.log(Boolean("Hello"));
console.log(Boolean(""));

Output:

true
false
true
false

JavaScript treats values as either truthy or falsy when converting them to Boolean.

Common falsy values include:

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

Most other values are truthy, including empty arrays [] and empty objects {}.

For example:

console.log(Boolean([]));  // true
console.log(Boolean({}));  // true

This behavior is important when writing conditions and validating form inputs.

2. Convert a String Using parseInt()

The parseInt() function converts the beginning of a string into an integer.

let value = "150px";

console.log(parseInt(value));

Output:

150

Unlike Number("150px"), which returns NaN, parseInt() can read the integer at the beginning of the string and stop when it reaches an invalid character.

Another example:

console.log(parseInt("45.99"));

Output:

45

parseInt() removes the fractional part because it returns an integer.

You can also specify a radix, usually 10 for decimal numbers:

console.log(parseInt("101", 2));

Output:

5

Here, "101" is interpreted as a binary number, which equals 5 in decimal.

3. Convert a String Using parseFloat()

The parseFloat() function reads a floating-point number from the beginning of a string.

let price = "99.99";

console.log(parseFloat(price));

Output:

99.99

It can also parse a numeric prefix:

console.log(parseFloat("25.50kg"));

Output:

25.5

Difference Between Number(), parseInt(), and parseFloat()

FunctionExampleResult
Number()Number("25")25
Number()Number("25px")NaN
parseInt()parseInt("25.9")25
parseInt()parseInt("25px")25
parseFloat()parseFloat("25.9")25.9
parseFloat()parseFloat("25.9px")25.9

Use Number() when you want to convert the entire string into a number. Use parseInt() or parseFloat() when parsing a numeric prefix is appropriate.

Remember that parsing a prefix does not validate the entire input. For example, parseFloat("25.9abc") returns 25.9, which may not be suitable for strict form validation.

4. Implicit Type Conversion in JavaScript

Implicit type conversion occurs when JavaScript automatically converts a value during an operation. This behavior is also called type coercion.

For example:

let result = "10" + 5;

console.log(result);

Output:

105

JavaScript converts the number 5 into a string and concatenates the two values.

But subtraction behaves differently:

let result = "10" - 5;

console.log(result);

Output:

5

The subtraction operator converts the string "10" into a number.

This is why the same values can produce different results with different operators.

String Concatenation

When one operand is a string, the + operator commonly performs string concatenation.

console.log("Hello " + 123);
console.log("Price: " + 500);

Output:

Hello 123
Price: 500

Automatic Numeric Conversion

Operators such as -, *, and / generally convert numeric strings into numbers.

console.log("20" - 5);
console.log("4" * 3);
console.log("20" / 2);

Output:

15
12
10

If the string cannot be converted into a valid number, the result may be NaN.

console.log("Hello" - 5);

Output:

NaN

5. Type Conversion in Comparisons

JavaScript also performs type conversion in some comparisons.

For example, the loose equality operator == allows type coercion.

console.log(5 == "5");

Output:

true

However, strict equality === compares values without converting their types.

console.log(5 === "5");

Output:

false

For most application code, prefer === and !== to avoid unexpected results caused by implicit conversion.

6. Convert Values to Strings Using Template Literals

Template literals provide a convenient way to include values inside strings.

let name = "Harshit";
let age = 25;

let message = `My name is ${name} and I am ${age} years old.`;

console.log(message);

Output:

My name is Harshit and I am 25 years old.

When a value is inserted into a template literal, JavaScript converts it into a string representation.

This is useful when creating messages, displaying data, and generating dynamic content.

7. Convert Dates and Other Objects

JavaScript objects can be converted into primitive values in different ways, depending on the object and operation.

For example, a Date object can be converted to a string:

let date = new Date("2026-01-15");

console.log(String(date));

You can also obtain its timestamp:

console.log(date.getTime());

The timestamp is a number representing milliseconds since January 1, 1970 UTC.

Avoid assuming that every object converts to a meaningful number or string. For example:

console.log(Number({}));

Output:

NaN

Understanding how objects convert to primitive values is useful when learning advanced JavaScript.

8. Common Type Conversion Mistakes

Mistake 1: Adding Numeric Strings

let a = "10";
let b = "20";

console.log(a + b);

Output:

1020

Solution:

console.log(Number(a) + Number(b));

Output:

30

Mistake 2: Assuming "false" Converts to false

console.log(Boolean("false"));

Output:

true

A non-empty string is truthy, even when its text says "false".

If you receive text such as "true" or "false" from an API or form, compare the string explicitly:

let value = "false";

let result = value === "true";

console.log(result);

Output:

false

Mistake 3: Treating NaN Like an Ordinary Number

let result = Number("Hello");

console.log(result === NaN);

Output:

false

NaN is not equal to itself, so use Number.isNaN():

console.log(Number.isNaN(result));

Output:

true

Mistake 4: Using parseInt() for Strict Validation

console.log(parseInt("123abc"));

Output:

123

This may be unexpected if you intend to accept only a valid numeric input. In such cases, validate the complete input instead of relying only on parseInt().

9. Practical Example: Calculating a Shopping Cart Total

Consider an e-commerce application where product prices and quantities come from input fields.

let price = "499";
let quantity = "2";

let total = Number(price) * Number(quantity);

console.log("Product Price:", price);
console.log("Quantity:", quantity);
console.log("Total Amount:", total);

Output:

Product Price: 499
Quantity: 2
Total Amount: 998

Explicit conversion ensures the values are treated as numbers during multiplication.

For real payment systems, also validate the input and use an appropriate money-handling strategy to avoid floating-point precision issues.

10. Quick Reference: JavaScript Type Conversion

MethodPurpose
Number(value)Converts a value to a number
String(value)Converts a value to a string
Boolean(value)Converts a value to a Boolean
parseInt(value)Parses an integer from a string
parseFloat(value)Parses a floating-point number
Number.isNaN(value)Checks whether a value is NaN
value.toString()Converts a supported value to a string

Frequently Asked Questions

What is type conversion in JavaScript?

Type conversion is the process of changing a value from one data type to another, such as converting a string into a number using Number().

What is the difference between implicit and explicit conversion?

Explicit conversion happens when you manually convert a value using functions such as Number() or String(). Implicit conversion happens automatically during operations when JavaScript converts values to the types it needs.

What is type coercion in JavaScript?

Type coercion is the automatic conversion of values from one type to another. For example, "10" - 5 returns the number 5 because JavaScript converts "10" into a number.

How do you convert a string to a number in JavaScript?

Use Number() for a complete numeric conversion:

let value = Number("123");

console.log(value); // 123

Why does "5" + 2 return "52"?

The + operator performs string concatenation when a string operand is involved. JavaScript converts 2 into "2" and combines the two strings.

What does NaN mean in JavaScript?

NaN stands for Not-a-Number. It is a special numeric value that indicates an invalid numeric result, such as Number("Hello").

Practice Exercises

Try these exercises to test your understanding:

  1. Convert the string "250" into a number.
  2. Convert the number 100 into a string.
  3. Convert 0, 1, and "" into Boolean values.
  4. Predict the output of "10" + 5.
  5. Predict the output of "10" - 5.
  6. Find the difference between Number("25px") and parseInt("25px").
  7. Check whether Number("Hello") returns NaN.
  8. Explain why Boolean("false") returns true.
  9. Calculate a shopping cart total using string values for price and quantity.
  10. Compare 5 == "5" and 5 === "5".

Conclusion

JavaScript type conversion helps you work with values of different data types. Explicit conversion gives you control over how values are converted, while implicit conversion happens automatically during operations.

For everyday development, understand Number(), String(), Boolean(), parseInt(), and parseFloat(). Also, learn how type coercion affects arithmetic, comparisons, and conditions.

Using explicit conversions and strict equality where appropriate makes your JavaScript code easier to understand, test, and maintain.

In the next tutorial, we will learn about JavaScript User Input, including how to read values from HTML forms and process them using JavaScript.

Leave a comment

Your email address will not be published.