javascript

Type Conversion Rules

Learn JavaScript type conversion rules. Understand how data types change from one to another, both automatically and manually, for smoother coding and fewer errors.

8 min read 8 sections Tutorial
Share

In JavaScript, data often needs to change from one type to another. This is called type conversion. You will learn the important rules for how JavaScript changes types. Knowing these rules helps you write code that works correctly and avoids common mistakes.

Type Conversion Rules

Type Conversion Rules

When you write code, you work with different kinds of data. Sometimes, a number needs to become text, or text needs to become a number. JavaScript has rules for how this happens. This tutorial will teach you these rules so your programs always behave as you expect.

What is Type Conversion?

Type conversion is when JavaScript changes a value from one data type to another, like turning a string into a number or a number into a boolean.

Automatic Conversion

JavaScript sometimes changes types for you without you asking, which is called implicit conversion or coercion.

Manual Conversion

You can also tell JavaScript to change types on purpose using special functions, which is explicit conversion.

Common Scenarios

Learn when and why type conversion happens, especially when working with user input or mathematical operations.

Avoiding Errors

Understanding conversion rules helps prevent bugs like unexpected 'NaN' (Not-a-Number) in your code.

Understanding Basic Type Conversion

Getting Started

Understanding Basic Type Conversion

Let's start with the simplest idea: sometimes JavaScript changes data types by itself. This happens when you mix different types in an operation. For example, if you try to add a number and a string, JavaScript will convert the number to a string first.

javascript
1let myNumber = 10; // This is a number
2let myString = "5"; // This is a string (text)
3
4// JavaScript converts myNumber to a string "10" before adding
5let result = myNumber + myString;
6
7console.log(result); // What do you think the result will be?
8console.log(typeof result); // Check the type of the result

Watch Out for Addition!

When you use the + operator, if either side is a string, JavaScript will convert the other side to a string too. This can lead to unexpected string concatenation instead of mathematical addition.

Implicit vs. Explicit Conversion

Implicit vs. Explicit Conversion

There are two main ways type conversion happens. Implicit conversion, also called coercion, is when JavaScript does it automatically. Explicit conversion is when you tell JavaScript exactly what type you want using special functions.

javascript
1let stringNum = "123"; // A number as a string
2let textBoolean = "true"; // A boolean as a string
3
4// Explicitly convert stringNum to a number
5let actualNum = Number(stringNum);
6console.log(actualNum, typeof actualNum); // Output: 123 'number'
7
8// Explicitly convert a number to a string
9let numToString = String(456);
10console.log(numToString, typeof numToString); // Output: "456" 'string'
11
12// Explicitly convert to a boolean
13let actualBoolean = Boolean(textBoolean); // Note: Most non-empty strings are true
14console.log(actualBoolean, typeof actualBoolean); // Output: true 'boolean'
15
16let zeroToBoolean = Boolean(0); // 0 converts to false
17console.log(zeroToBoolean, typeof zeroToBoolean); // Output: false 'boolean'
✗ BadImplicit (Can Be Tricky)
let value1 = "10";
let value2 = 5;
let sum = value1 + value2; // "10" + 5 becomes "105"
console.log(sum);
✓ GoodExplicit (Clearer)
let value1 = "10";
let value2 = 5;
let sum = Number(value1) + value2; // 10 + 5 becomes 15
console.log(sum);

Converting to Numbers and Strings

Converting to Numbers and Strings

Converting values to numbers or strings is very common. JavaScript offers several ways to do this. Each method has slightly different rules, especially when dealing with text that isn't a perfect number.

Using Number() or parseInt()
// Number() converts the whole value
console.log(Number("42")); // 42
console.log(Number("42px")); // NaN (Not-a-Number)
console.log(Number(" 123 ")); // 123
// parseInt() looks for whole numbers at the start
console.log(parseInt("42")); // 42
console.log(parseInt("42px")); // 42 (stops at 'p')
console.log(parseInt("px42")); // NaN (starts with non-number)
VS
Using Unary Plus (+) or String()
// Unary plus (+) is a quick way to convert to a number
console.log(+"42"); // 42
console.log(+"42px"); // NaN
console.log(+" 123 "); // 123
// String() converts any value to its string representation
console.log(String(123)); // "123"
console.log(String(true)); // "true"
console.log(String(null)); // "null"
console.log(String(undefined)); // "undefined"

Choose the Right Tool

Use Number() for strict conversion of a whole value to a number. Use parseInt() or parseFloat() when you need to extract a number from the beginning of a string. Use String() or value.toString() when you need any value to be text.

Real-World Type Conversion Scenarios

Real-World Type Conversion Scenarios

Type conversion is not just for theory; it's used all the time in real web projects. A common place is when you get input from a user. Data from HTML forms always comes as strings, even if the user types numbers.

1

Create an HTML Input

First, imagine you have an HTML input field where a user types their age. This input will give you a string.

html
1<input type="number" id="ageInput" value="25">
2

Get the Input Value

In JavaScript, you get the value from this input. It will always be a string, even if type="number" in HTML.

javascript
1let ageString = document.getElementById('ageInput').value;
2console.log(ageString, typeof ageString); // Example: "25" 'string'
3

Convert to a Number

If you want to do math with the age, like adding 1 to it, you must convert the string to a number first.

javascript
1let ageNumber = Number(ageString); // Explicitly convert to number
2let nextYearAge = ageNumber + 1;
3console.log(nextYearAge, typeof nextYearAge); // Example: 26 'number'
4

Use the Number

Now you can use ageNumber in calculations or comparisons. This is a crucial step for working with user data.

javascript
1if (ageNumber >= 18) {
2 console.log("This person is an adult.");
3} else {
4 console.log("This person is a minor.");
5}

Ignoring Input Types

If you forget to convert user input from a string to a number, you might end up adding strings together (e.g., '5' + 1 becomes '51') instead of getting a mathematical sum (e.g., 5 + 1 becomes 6). This is a common source of bugs!

Common Conversion Rules Overview

Common Conversion Rules Overview

Original ValueConverts to NumberConverts to BooleanConverts to String
`"hello"``NaN``true``"hello"`
`"123"``123``true``"123"`
`1``1``true``"1"`
`0``0``false``"0"`
`true``1``true``"true"`
`false``0``false``"false"`
`null``0``false``"null"`
`undefined``NaN``false``"undefined"`
`[]` (empty array)`0``true``""` (empty string)
`{}` (empty object)`NaN``true``"[object Object]"`

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

What is the result of "10" + 5 in JavaScript?

Quick Check

Which of these values is considered 'falsy' when converted to a boolean?

Quick Check

What will Number("20 apples") return?

Quick Check

How can you explicitly convert the string "3.14" to a floating-point number?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Type Conversion — JavaScript changes data from one type to another, like a string to a number.
  • 2Implicit Conversion (Coercion) — JavaScript automatically changes types for you, especially in operations like "1" + 2.
  • 3Explicit Conversion — You manually tell JavaScript to change types using functions like Number(), String(), or Boolean().
  • 4Number() — Converts a value strictly to a number; returns NaN if it can't convert the whole value.
  • 5parseInt() / parseFloat() — Extracts a number from the beginning of a string, stopping at the first non-numeric character.
  • 6String() — Converts any value into its string representation.
  • 7Boolean() — Converts any value to true or false; 0, '', null, undefined, NaN, and false are falsy.
  • 8Unary Plus (+) — A shortcut to convert a value to a number, e.g., +"5" becomes 5.
  • 9Subtraction (-) — Forces operands to numbers if possible, e.g., "10" - "5" becomes 5.
  • 10User Input — Data from HTML input fields is always a string; remember to convert it to a number if you need to do math.

JavaScript Data Types

Dive deeper into all the fundamental data types JavaScript uses, like numbers, strings, and booleans.

Operators in JavaScript

Explore how different operators work and how they influence type conversion in your code.

Understanding `NaN`

Learn more about the 'Not-a-Number' value and how to handle it effectively in your programs.

Conditional Statements

See how type conversion to booleans (truthy/falsy) affects if/else statements and logical flow.

You Mastered Type Conversion!

Great job! You now understand the essential rules of JavaScript type conversion. This knowledge is key to writing robust code that handles different data types correctly and avoids common pitfalls. Keep practicing, and your code will be much more reliable!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning