LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 840 min read

JavaScript Type Conversion

Learn how JavaScript converts values between different data types using explicit conversion, implicit conversion, coercion, truthy and falsy values, and practical conversion techniques.

Introduction

JavaScript applications constantly receive data from users, forms, APIs, URLs, browser storage, and external systems. The data received may not always have the type required by the program.

For example, a user may enter the number 25 into an HTML input field, but JavaScript commonly receives the value as the string "25". Before performing numeric calculations, the program may need to convert that string into a number.

Type conversion is the process of changing a value from one data type into another. JavaScript can perform conversions explicitly when the developer requests them or implicitly when the language automatically converts values during an operation.

Understanding type conversion is essential because unexpected conversions are one of the most common causes of confusing JavaScript behavior.

What You Will Learn
  • What type conversion means.
  • Why JavaScript applications need type conversion.
  • The difference between explicit and implicit conversion.
  • What type coercion means.
  • How to convert values into strings.
  • How String() works.
  • How toString() works.
  • How to convert values into numbers.
  • How Number() works.
  • How parseInt() works.
  • How parseFloat() works.
  • How booleans convert into numbers.
  • How null and undefined convert into numbers.
  • How to convert values into booleans.
  • What truthy values are.
  • What falsy values are.
  • How implicit string conversion works.
  • How implicit numeric conversion works.
  • Why the + operator behaves differently from other arithmetic operators.
  • How comparison operators perform coercion.
  • The difference between loose and strict equality.
  • How NaN appears during failed numeric conversion.
  • How to validate conversion results.
  • How type conversion is used with real form input.

What is Type Conversion?

Type conversion is the process of changing a value from one data type into another data type.

Basic Type Conversion
const textAge = '25';
console.log(textAge);
console.log(typeof textAge);
const numericAge = Number(textAge);
console.log(numericAge);
console.log(typeof numericAge);
Output

Click Run to see what this code prints.

Conversion Process
'25'
│
│ Number()
▼
25
String ─────────▶ Number

The original value is a string. Number() converts it into a numeric value that can be used in calculations.

Simple Definition
  • Type conversion changes the type of a value.
  • The original data may come from users or external systems.
  • The converted value can then be used for the required operation.
  • JavaScript supports both manual and automatic conversions.

Why Do We Need Type Conversion?

Different operations require different types of data. A value may need to be converted before it can be calculated, displayed, compared, validated, or stored.

Form Input

Values received from HTML input elements are commonly strings and may need conversion before calculations.

Calculations

Numeric strings must often be converted into numbers before performing arithmetic.

API Data

External data may need conversion into the types expected by the application.

Browser Storage

Stored values may need conversion after being retrieved from local or session storage.

Validation

Values may be converted into booleans to determine whether they should be treated as true or false.

Display

Numbers, booleans, and other values may need string conversion for text-based output.

Why Conversion Matters
const firstValue = '10';
const secondValue = '20';
console.log(firstValue + secondValue);
const firstNumber = Number(firstValue);
const secondNumber = Number(secondValue);
console.log(firstNumber + secondNumber);
Output

Click Run to see what this code prints.

Without conversion, the + operator joins the two strings. After conversion, JavaScript performs numeric addition.

Real-World Analogy

Think of type conversion like changing money from one currency into another. The value is transformed into a different form so that it can be used in a different system.

Type Conversion Analogy
Original Value
│
▼
┌──────────────┐
│ '100' │
│ String │
└──────────────┘
│
│ Number()
▼
┌──────────────┐
│ 100 │
│ Number │
└──────────────┘
│
│ String()
▼
┌──────────────┐
│ '100' │
│ String │
└──────────────┘

The information may appear similar to a human, but JavaScript treats the string "100" and the number 100 as different types of values.

Types of Conversion

JavaScript type conversion can be divided into two major categories: explicit conversion and implicit conversion.

Conversion Categories
Type Conversion
│
├── Explicit Conversion
│ │
│ ├── String()
│ ├── Number()
│ ├── Boolean()
│ ├── parseInt()
│ └── parseFloat()
│
└── Implicit Conversion
│
└── Automatic Type Coercion

Explicit Conversion

The developer intentionally converts a value using a conversion function or method.

Implicit Conversion

JavaScript automatically converts a value while evaluating an expression or operation.

Explicit Type Conversion

Explicit type conversion happens when the developer intentionally requests a conversion.

Explicit Conversion
const textValue = '100';
const numberValue = Number(textValue);
const booleanValue = Boolean(textValue);
console.log(numberValue);
console.log(typeof numberValue);
console.log(booleanValue);
console.log(typeof booleanValue);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

Fix the code below so it explicitly converts the text value into a number instead of a string, then logs the value and its type.

expected output: 42 number
Explicit Conversion
Developer Chooses Conversion
'100'
│
├── Number('100') ──▶ 100
│
├── Boolean('100') ──▶ true
│
└── String(100) ──▶ '100'
Why Explicit Conversion is Preferred
  • The developer controls when conversion happens.
  • The code clearly communicates its intention.
  • The result is easier to understand.
  • Unexpected coercion bugs are easier to avoid.

Implicit Type Conversion

Implicit type conversion happens automatically when JavaScript converts one or more values during an operation.

Implicit Conversion
console.log('10' + 5);
console.log('10' - 5);
Output

Click Run to see what this code prints.

The + operator converts the number 5 into a string and performs concatenation. The - operator converts the string "10" into a number and performs subtraction.

Automatic Conversion
'10' + 5
│
▼
'10' + '5'
│
▼
'105'
'10' - 5
│
▼
10 - 5
│
▼
5

Type Coercion

Type coercion is the automatic conversion of a value from one type into another by JavaScript.

Type Coercion Examples
console.log('5' + 2);
console.log('5' - 2);
console.log('5' * 2);
console.log('10' / 2);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

This code should add the two numeric strings together as numbers, not join them as text. Fix it so it prints the correct sum.

expected output: 12

The behavior depends on the operator. The + operator can perform string concatenation, while subtraction, multiplication, and division normally attempt numeric conversion.

Coercion Can Be Confusing
  • Different operators can trigger different conversions.
  • The + operator is especially important because it supports both addition and concatenation.
  • Automatic conversion can produce unexpected results.
  • Explicit conversion usually makes code easier to understand.

String Conversion

String conversion changes a value into textual data. The most common techniques are String() and the toString() method.

Basic String Conversion
const age = 25;
const isActive = true;
const ageText = String(age);
const activeText = String(isActive);
console.log(ageText);
console.log(typeof ageText);
console.log(activeText);
console.log(typeof activeText);
Output

Click Run to see what this code prints.

Using String()

The String() function can convert many JavaScript values into strings.

String() Examples
console.log(String(100));
console.log(String(99.99));
console.log(String(true));
console.log(String(false));
console.log(String(null));
console.log(String(undefined));
Output

Click Run to see what this code prints.

Check Converted Types
const numberText = String(100);
const booleanText = String(true);
console.log(typeof numberText);
console.log(typeof booleanText);
Output

Click Run to see what this code prints.

Using toString()

Many JavaScript values provide a toString() method that returns a string representation of the value.

toString() Examples
const age = 25;
const price = 499.99;
const isActive = true;
console.log(age.toString());
console.log(price.toString());
console.log(isActive.toString());
Output

Click Run to see what this code prints.

Check Result Type
const value = 100;
const result = value.toString();
console.log(result);
console.log(typeof result);
Output

Click Run to see what this code prints.

String() vs toString()
  • String() can safely convert null and undefined.
  • Calling toString() directly on null or undefined causes an error.
  • String() is often safer for general conversion.
  • toString() is useful when you already know the value supports the method.

String Conversion Examples

Different Values to Strings
const values = [
100,
99.99,
true,
false,
null,
undefined
];
console.log(String(values[0]), typeof String(values[0]));
console.log(String(values[1]), typeof String(values[1]));
console.log(String(values[2]), typeof String(values[2]));
console.log(String(values[3]), typeof String(values[3]));
console.log(String(values[4]), typeof String(values[4]));
console.log(String(values[5]), typeof String(values[5]));
Output

Click Run to see what this code prints.

Number Conversion

Number conversion changes a value into numeric data. JavaScript provides Number(), parseInt(), and parseFloat() for common numeric conversions.

Basic Number Conversion
const ageText = '25';
const age = Number(ageText);
console.log(age);
console.log(typeof age);
Output

Click Run to see what this code prints.

Using Number()

The Number() function attempts to convert an entire value into a number.

Number() Examples
console.log(Number('100'));
console.log(Number('99.99'));
console.log(Number(true));
console.log(Number(false));
console.log(Number(null));
console.log(Number(undefined));
Output

Click Run to see what this code prints.

String to Number

Numeric strings can be converted into numbers using Number().

Numeric String Conversion
const firstValue = '100';
const secondValue = '50.5';
const firstNumber = Number(firstValue);
const secondNumber = Number(secondValue);
console.log(firstNumber);
console.log(secondNumber);
console.log(typeof firstNumber);
console.log(typeof secondNumber);
Output

Click Run to see what this code prints.

If the entire string cannot be converted into a valid number, Number() returns NaN.

Invalid Number Conversion
console.log(Number('Hello'));
console.log(Number('100px'));
Output

Click Run to see what this code prints.

Boolean to Number

When converted into numbers, true becomes 1 and false becomes 0.

Boolean Number Conversion
console.log(Number(true));
console.log(Number(false));
Output

Click Run to see what this code prints.

Boolean Conversion
true ─────▶ 1
false ─────▶ 0

Null and Undefined to Number

null and undefined produce different results when converted into numbers.

Null and Undefined Conversion
console.log(Number(null));
console.log(Number(undefined));
Output

Click Run to see what this code prints.

Important Difference
  • Number(null) returns 0.
  • Number(undefined) returns NaN.
  • These automatic rules can be surprising.
  • Always validate external values before calculations.

Empty Values to Number

Empty strings and strings containing only whitespace convert to zero when passed to Number().

Empty String Conversion
console.log(Number(''));
console.log(Number(' '));
Output

Click Run to see what this code prints.

This behavior is important when processing user input because an empty input value can unexpectedly become zero.

Using parseInt()

parseInt() converts a string into an integer. It reads numeric characters from the beginning of the string and stops when it reaches an invalid character.

parseInt() Examples
console.log(parseInt('100'));
console.log(parseInt('99.99'));
console.log(parseInt('50px'));
console.log(parseInt('25 years'));
Output

Click Run to see what this code prints.

If the string does not begin with a valid numeric value, parseInt() returns NaN.

Invalid parseInt()
console.log(parseInt('Hello100'));
Output

Click Run to see what this code prints.

Using a Radix
console.log(parseInt('1010', 2));
console.log(parseInt('20', 10));
console.log(parseInt('FF', 16));
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

This code should extract just the leading number from the input, but Number() fails on non-numeric characters. Fix it using the correct function so it prints 120.

expected output: 120
parseInt() Best Practice
  • Use parseInt() when you need an integer from a string.
  • It can read a numeric prefix from some strings.
  • It removes the decimal portion of decimal input.
  • Specify the radix when the numeric base matters.

Using parseFloat()

parseFloat() converts a string into a floating-point number and preserves a valid decimal portion.

parseFloat() Examples
console.log(parseFloat('99.99'));
console.log(parseFloat('50.5px'));
console.log(parseFloat('25.75 kg'));
Output

Click Run to see what this code prints.

parseInt() vs parseFloat()
const value = '99.99';
console.log(parseInt(value));
console.log(parseFloat(value));
Output

Click Run to see what this code prints.

Number Conversion Comparison

Number Conversion Methods
Input Number() parseInt() parseFloat()
-------------------------------------------------------
'100' 100 100 100
'99.99' 99.99 99 99.99
'50px' NaN 50 50
'25.5kg' NaN 25 25.5
'Hello' NaN NaN NaN
'' 0 NaN NaN
Which Method Should You Use?
  • Use Number() when the entire value must represent a valid number.
  • Use parseInt() when you need an integer from the beginning of a string.
  • Use parseFloat() when you need a decimal number from the beginning of a string.
  • Always validate the result when conversion may fail.

Boolean Conversion

Boolean conversion changes a value into either true or false.

Basic Boolean Conversion
console.log(Boolean(1));
console.log(Boolean(0));
console.log(Boolean('JavaScript'));
console.log(Boolean(''));
Output

Click Run to see what this code prints.

Using Boolean()

The Boolean() function converts any value into true or false according to JavaScript truthiness rules.

Boolean() Examples
console.log(Boolean(100));
console.log(Boolean(-10));
console.log(Boolean(0));
console.log(Boolean('Hello'));
console.log(Boolean(''));
console.log(Boolean(null));
console.log(Boolean(undefined));
Output

Click Run to see what this code prints.

Truthy Values

A truthy value is a value that becomes true when JavaScript converts it into a boolean.

Truthy Values
console.log(Boolean(1));
console.log(Boolean(-1));
console.log(Boolean(100));
console.log(Boolean('Hello'));
console.log(Boolean('false'));
console.log(Boolean([]));
console.log(Boolean({}));
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

Beginners often assume the string '0' is falsy. Fix the code below so it correctly prints 'Truthy' for the string '0', since non-empty strings are always truthy.

expected output: Truthy
Common Truthy Values
Truthy Values
--------------------------------
Non-zero numbers
Negative numbers
Non-empty strings
'0'
'false'
Arrays
Objects
Functions
Most other values
Strings Can Be Surprising
  • The string "false" is truthy.
  • The string "0" is truthy.
  • Any non-empty string is truthy.
  • The text inside the string does not determine its boolean value.

Falsy Values

A falsy value is a value that becomes false when converted into a boolean.

Falsy Values
console.log(Boolean(false));
console.log(Boolean(0));
console.log(Boolean(-0));
console.log(Boolean(0n));
console.log(Boolean(''));
console.log(Boolean(null));
console.log(Boolean(undefined));
console.log(Boolean(NaN));
Output

Click Run to see what this code prints.

Common Falsy Values
Falsy Values
--------------------------------
false
0
-0
0n
''
null
undefined
NaN
Remember the Falsy Values
  • false
  • 0 and -0
  • 0n
  • Empty string
  • null
  • undefined
  • NaN

Truthy and Falsy Values in Conditions

Conditional statements automatically evaluate values according to their truthy or falsy behavior.

Truthy Condition
const userName = 'Rahul';
if (userName) {
console.log('User name exists');
}
Output

Click Run to see what this code prints.

Falsy Condition
const userName = '';
if (userName) {
console.log('User name exists');
} else {
console.log('User name is empty');
}
Output

Click Run to see what this code prints.

Implicit String Conversion

JavaScript may automatically convert values into strings, especially when the + operator is used with a string.

Implicit String Conversion
console.log('Age: ' + 25);
console.log('Active: ' + true);
console.log('Value: ' + null);
Output

Click Run to see what this code prints.

Automatic String Conversion
'Age: ' + 25
│
▼
'Age: ' + '25'
│
▼
'Age: 25'

Implicit Number Conversion

Arithmetic operators such as subtraction, multiplication, and division commonly convert numeric strings into numbers.

Implicit Numeric Conversion
console.log('20' - 5);
console.log('10' * 2);
console.log('100' / 4);
console.log('10' % 3);
Output

Click Run to see what this code prints.

Numeric Coercion
'20' - 5
│
▼
20 - 5
│
▼
15

The + Operator Behavior

The + operator is special because it performs both numeric addition and string concatenation.

Addition vs Concatenation
console.log(10 + 20);
console.log('10' + 20);
console.log(10 + '20');
console.log('10' + '20');
Output

Click Run to see what this code prints.

When string concatenation is selected, values are converted into strings and joined.

Order Matters
console.log(10 + 20 + '30');
console.log('10' + 20 + 30);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

This code is meant to calculate the total price by adding two numbers, but one value is a string, causing concatenation instead of addition. Fix it so the output is the correct numeric sum.

expected output: 70
Evaluation Order
10 + 20 + '30'
10 + 20
│
▼
30 + '30'
│
▼
'3030'
'10' + 20 + 30
'10' + 20
│
▼
'1020' + 30
│
▼
'102030'
The + Operator is a Common Source of Bugs
  • Number + Number performs addition.
  • String involvement can trigger concatenation.
  • Expressions are evaluated from left to right.
  • Convert values explicitly before calculations.

Other Arithmetic Operators

Unlike +, operators such as -, *, /, and % do not perform string concatenation. They normally attempt numeric conversion.

Arithmetic Coercion
console.log('20' - '5');
console.log('20' * '5');
console.log('20' / '5');
console.log('20' % '6');
Output

Click Run to see what this code prints.

Failed Arithmetic Conversion
console.log('Hello' - 5);
console.log('JavaScript' * 2);
Output

Click Run to see what this code prints.

Comparison Coercion

Some comparison operations may convert values before comparing them.

Comparison Examples
console.log('10' > 5);
console.log('20' < 30);
console.log(true > 0);
Output

Click Run to see what this code prints.

Relational comparisons may convert values into compatible forms before evaluating the result.

Loose vs Strict Equality

The loose equality operator == allows type coercion before comparison. The strict equality operator === compares both value and type without performing this kind of coercion.

Loose Equality
console.log(5 == '5');
console.log(0 == false);
console.log('' == false);
Output

Click Run to see what this code prints.

Strict Equality
console.log(5 === '5');
console.log(0 === false);
console.log('' === false);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

This validation is supposed to reject the string '100' because it is not strictly a number, but loose equality lets it slip through. Fix it using strict equality so it correctly prints 'Invalid input'.

expected output: Invalid input
Equality Comparison
Loose Equality ==
5 == '5'
│
├── Type Conversion
│
└── 5 == 5
│
▼
true
Strict Equality ===
5 === '5'
│
├── Number !== String
│
└── No Conversion
│
▼
false
Recommended Practice
  • Prefer === for equality comparisons.
  • Prefer !== for inequality comparisons.
  • Strict comparison avoids automatic equality coercion.
  • Use loose equality only when you intentionally understand and require its coercion rules.

Common Conversion Results

Conversion Table
Original Value String() Number() Boolean()
------------------------------------------------------------
'100' '100' 100 true
'0' '0' 0 true
'' '' 0 false
100 '100' 100 true
0 '0' 0 false
true 'true' 1 true
false 'false' 0 false
null 'null' 0 false
undefined 'undefined' NaN false
NaN 'NaN' NaN false
Important Conversion Results
  • Number("") returns 0.
  • Number(null) returns 0.
  • Number(undefined) returns NaN.
  • Number(true) returns 1.
  • Number(false) returns 0.
  • Boolean("0") returns true because it is a non-empty string.
  • Boolean("false") returns true because it is a non-empty string.
  • Boolean([]) and Boolean({}) both return true.

NaN During Conversion

Failed numeric conversions often produce NaN. NaN means Not-a-Number and represents an invalid numeric result.

Failed Conversion
const value = Number('JavaScript');
console.log(value);
console.log(typeof value);
Output

Click Run to see what this code prints.

More NaN Examples
console.log(Number('Hello'));
console.log(parseInt('JavaScript'));
console.log(parseFloat('CSS'));
Output

Click Run to see what this code prints.

Checking Conversion Results

When numeric conversion can fail, the result should be validated before it is used in calculations.

Check with Number.isNaN()
const value = Number('Hello');
if (Number.isNaN(value)) {
console.log('Conversion failed');
} else {
console.log('Valid number:', value);
}
Output

Click Run to see what this code prints.

Successful Validation
const value = Number('250');
if (Number.isNaN(value)) {
console.log('Conversion failed');
} else {
console.log('Valid number:', value);
}
Output

Click Run to see what this code prints.

Validate External Data
  • User input may contain invalid text.
  • API data may not have the expected type.
  • Browser storage values may require conversion.
  • Always check conversion results before important calculations.

Real-World Form Input Example

HTML form input values are commonly received as strings. Numeric input should be converted before arithmetic.

Without Conversion
const price = '100';
const quantity = '2';
console.log(price + quantity);
Output

Click Run to see what this code prints.

With Conversion
const priceInput = '100';
const quantityInput = '2';
const price = Number(priceInput);
const quantity = Number(quantityInput);
const total = price * quantity;
console.log(total);
Output

Click Run to see what this code prints.

Form Data Flow
HTML Input
│
▼
'100'
String
│
│ Number()
▼
100
Number
│
│ Calculation
▼
Result

Complete Type Conversion Example

The following example demonstrates type conversion in a simple shopping application.

shopping-calculator.js
// Values received as strings
const productName = 'JavaScript Course';
const priceInput = '499.99';
const quantityInput = '2';
const discountInput = '10';
const premiumInput = 'true';
// Convert numeric values
const price = Number(priceInput);
const quantity = Number(quantityInput);
const discountPercent = Number(discountInput);
// Convert application flag
const isPremium = premiumInput === 'true';
// Calculate values
const subtotal = price * quantity;
const discountAmount = subtotal * (discountPercent / 100);
const finalTotal = subtotal - discountAmount;
// Convert values for display
const quantityText = String(quantity);
const premiumText = String(isPremium);
// Display information
console.log('Product:', productName);
console.log('Price:', price);
console.log('Quantity:', quantityText);
console.log('Premium User:', premiumText);
console.log('Subtotal:', subtotal);
console.log('Discount:', discountAmount);
console.log('Final Total:', finalTotal);
// Validate converted values
console.log('Price is Number:', !Number.isNaN(price));
console.log('Quantity is Number:', !Number.isNaN(quantity));
console.log('Premium Type:', typeof isPremium);
Output

Click Run to see what this code prints.

Application Conversion Flow
External Data
│
├── '499.99' ──▶ Number() ──▶ 499.99
│
├── '2' ───────▶ Number() ──▶ 2
│
├── '10' ──────▶ Number() ──▶ 10
│
└── 'true' ────▶ Comparison ▶ true
│
▼
Calculations
│
▼
Output

Real-World Applications

Type conversion is used throughout modern JavaScript applications.

Forms

Convert text input into numbers, booleans, dates, and other required values.

Shopping Carts

Convert price and quantity values before calculating totals and discounts.

Authentication

Convert and validate status values used for permissions and login state.

APIs

Normalize values received from external services into the types expected by the application.

Local Storage

Convert retrieved string values back into useful application types.

Data Processing

Convert imported text data into numbers before calculations and analysis.

Games

Convert user input, scores, settings, and stored values into appropriate types.

Configuration

Convert environment and configuration values into numbers or booleans.

Common Beginner Mistakes

Avoid These Mistakes
  • Assuming numeric-looking strings are already numbers.
  • Using + with numeric strings and expecting addition.
  • Forgetting that HTML input values are commonly strings.
  • Assuming all operators perform the same coercion.
  • Using Number() on text such as "100px" and expecting 100.
  • Using parseInt() when decimal precision is required.
  • Using parseFloat() when the entire string must be strictly numeric.
  • Forgetting that Number("") returns 0.
  • Forgetting that Number(null) returns 0.
  • Forgetting that Number(undefined) returns NaN.
  • Assuming Boolean("false") returns false.
  • Assuming Boolean("0") returns false.
  • Forgetting that empty arrays and empty objects are truthy.
  • Using == when strict comparison is intended.
  • Not validating failed numeric conversions.
  • Comparing NaN using NaN === NaN.
  • Calling toString() directly on null or undefined.
  • Relying too heavily on automatic coercion.
  • Changing types without understanding the required result.
  • Performing calculations before converting external data.
Common Conversion Mistakes
// ❌ String concatenation instead of addition
console.log('10' + '20');
// ❌ Number() requires the complete string to be numeric
console.log(Number('100px'));
// ❌ Non-empty strings are truthy
console.log(Boolean('false'));
// ❌ Loose equality performs coercion
console.log(5 == '5');
// ❌ NaN is not equal to itself
console.log(NaN === NaN);
Output

Click Run to see what this code prints.

Best Practices

  • Prefer explicit conversion when the expected type matters.
  • Use Number() when the complete value must represent a valid number.
  • Use parseInt() when extracting an integer from the beginning of a string.
  • Use parseFloat() when extracting a decimal value from the beginning of a string.
  • Use String() for safe general string conversion.
  • Use Boolean() when you intentionally need boolean conversion.
  • Learn the complete list of falsy values.
  • Remember that non-empty strings are truthy.
  • Convert form values before performing numeric calculations.
  • Validate numeric conversion results using Number.isNaN().
  • Prefer === instead of == for predictable comparisons.
  • Prefer !== instead of != for predictable inequality checks.
  • Do not depend on complex implicit coercion.
  • Use parentheses when expression evaluation could be unclear.
  • Remember that the + operator supports both addition and concatenation.
  • Understand that -, *, /, and % usually trigger numeric conversion.
  • Do not assume Number(), parseInt(), and parseFloat() behave identically.
  • Handle empty strings carefully before numeric conversion.
  • Validate values received from APIs and external systems.
  • Document intentional conversions when the reason is not obvious.
Recommended Conversion Style
const priceInput = '499.99';
const quantityInput = '2';
const price = Number(priceInput);
const quantity = Number(quantityInput);
if (
Number.isNaN(price) ||
Number.isNaN(quantity)
) {
console.log('Invalid input');
} else {
const total = price * quantity;
console.log('Total:', total);
}
Output

Click Run to see what this code prints.

Frequently Asked Questions

Type conversion is the process of changing a value from one data type into another.

The two main types are explicit conversion and implicit conversion.

Explicit conversion happens when the developer intentionally converts a value using functions or methods such as String(), Number(), or Boolean().

Implicit conversion happens automatically when JavaScript converts values during an operation.

Type coercion is JavaScript automatically converting a value from one type into another.

Use String(value) or, when supported and appropriate, value.toString().

Yes. String(null) returns "null" and String(undefined) returns "undefined".

No. Calling toString() directly on null or undefined causes an error.

Use Number(), parseInt(), or parseFloat() depending on the required behavior.

It returns the number 100.

It returns NaN because the entire string is not a valid numeric representation.

It returns 100 because parseInt() reads the valid integer prefix.

It returns 99.99 because parseFloat() reads the valid decimal prefix.

It returns 1.

It returns 0.

It returns 0.

It returns NaN.

It returns 0.

A truthy value is a value that becomes true when converted into a boolean.

A falsy value is a value that becomes false when converted into a boolean.

It is truthy because it is a non-empty string.

It is truthy because it is a non-empty string.

Yes. Empty arrays are truthy.

Yes. Empty objects are truthy.

The + operator performs string concatenation when string conversion is selected.

The subtraction operator converts the numeric string into a number before subtraction.

The == operator allows type coercion, while === compares value and type without this equality coercion.

Use strict equality === for most comparisons.

Use Number.isNaN() on the converted result.

Form input values are commonly strings, so numeric values usually need conversion before calculations.

Key Takeaways

  • Type conversion changes a value from one data type into another.
  • JavaScript supports explicit and implicit conversion.
  • Explicit conversion is intentionally requested by the developer.
  • Implicit conversion happens automatically.
  • Automatic conversion is commonly called type coercion.
  • String() converts values into strings.
  • toString() can convert supported values into strings.
  • String() can safely convert null and undefined.
  • Number() attempts to convert the entire value into a number.
  • Invalid Number() conversion returns NaN.
  • parseInt() converts a numeric prefix into an integer.
  • parseFloat() converts a numeric prefix into a decimal number.
  • Number(true) returns 1.
  • Number(false) returns 0.
  • Number(null) returns 0.
  • Number(undefined) returns NaN.
  • Number("") returns 0.
  • Boolean() converts values into true or false.
  • Truthy values become true in boolean contexts.
  • Falsy values become false in boolean contexts.
  • Non-empty strings are truthy.
  • The strings "false" and "0" are truthy.
  • The + operator performs both addition and concatenation.
  • Subtraction, multiplication, division, and remainder commonly trigger numeric conversion.
  • The == operator allows coercion.
  • The === operator compares value and type without equality coercion.
  • Strict equality is usually preferred.
  • Failed numeric conversions commonly produce NaN.
  • Number.isNaN() can validate failed numeric conversions.
  • External data should be converted and validated before use.
  • Explicit conversion usually produces clearer and more predictable code.

Summary

Type conversion is the process of changing a value from one data type into another. It is essential in JavaScript because applications constantly receive values from forms, APIs, browser storage, URLs, and other external systems.

Explicit conversion occurs when the developer intentionally converts a value using functions such as String(), Number(), and Boolean(), or parsing functions such as parseInt() and parseFloat(). Explicit conversion makes the intended behavior easier to understand.

Implicit conversion happens automatically during operations and is commonly called type coercion. The behavior depends on the operator. The + operator can perform string concatenation, while subtraction, multiplication, division, and remainder commonly attempt numeric conversion.

Boolean conversion introduces the concepts of truthy and falsy values. Values such as false, 0, an empty string, null, undefined, and NaN are falsy, while most other values are truthy. Non-empty strings remain truthy even when their text is "false" or "0".

Loose equality allows type coercion before comparison, while strict equality compares both value and type without this equality coercion. Using strict equality generally produces clearer and more predictable code.

Numeric conversion can fail and produce NaN. Conversion results should therefore be validated when working with user input or external data. Explicit conversion combined with proper validation helps prevent many common JavaScript bugs.

Lesson 8 Completed
  • You understand what type conversion means.
  • You know why JavaScript applications need type conversion.
  • You understand explicit conversion.
  • You understand implicit conversion.
  • You know what type coercion means.
  • You can convert values into strings.
  • You understand String() and toString().
  • You can convert values into numbers.
  • You understand Number(), parseInt(), and parseFloat().
  • You know how booleans convert into numbers.
  • You know how null and undefined convert into numbers.
  • You can convert values into booleans.
  • You understand truthy values.
  • You understand falsy values.
  • You understand implicit string conversion.
  • You understand implicit numeric conversion.
  • You understand the special behavior of the + operator.
  • You understand loose and strict equality.
  • You know how NaN appears during failed conversion.
  • You know how to validate conversion results.
  • You are ready to learn JavaScript Operators.
Next Lesson →

JavaScript Operators