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
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.
1let myNumber = 10; // This is a number2let myString = "5"; // This is a string (text)34// JavaScript converts myNumber to a string "10" before adding5let result = myNumber + myString;67console.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.
1let stringNum = "123"; // A number as a string2let textBoolean = "true"; // A boolean as a string34// Explicitly convert stringNum to a number5let actualNum = Number(stringNum);6console.log(actualNum, typeof actualNum); // Output: 123 'number'78// Explicitly convert a number to a string9let numToString = String(456);10console.log(numToString, typeof numToString); // Output: "456" 'string'1112// Explicitly convert to a boolean13let actualBoolean = Boolean(textBoolean); // Note: Most non-empty strings are true14console.log(actualBoolean, typeof actualBoolean); // Output: true 'boolean'1516let zeroToBoolean = Boolean(0); // 0 converts to false17console.log(zeroToBoolean, typeof zeroToBoolean); // Output: false 'boolean'
let value1 = "10";let value2 = 5;let sum = value1 + value2; // "10" + 5 becomes "105"console.log(sum);
let value1 = "10";let value2 = 5;let sum = Number(value1) + value2; // 10 + 5 becomes 15console.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.
// Number() converts the whole valueconsole.log(Number("42")); // 42console.log(Number("42px")); // NaN (Not-a-Number)console.log(Number(" 123 ")); // 123// parseInt() looks for whole numbers at the startconsole.log(parseInt("42")); // 42console.log(parseInt("42px")); // 42 (stops at 'p')console.log(parseInt("px42")); // NaN (starts with non-number)
// Unary plus (+) is a quick way to convert to a numberconsole.log(+"42"); // 42console.log(+"42px"); // NaNconsole.log(+" 123 "); // 123// String() converts any value to its string representationconsole.log(String(123)); // "123"console.log(String(true)); // "true"console.log(String(null)); // "null"console.log(String(undefined)); // "undefined"
// Number() converts the whole valueconsole.log(Number("42")); // 42console.log(Number("42px")); // NaN (Not-a-Number)console.log(Number(" 123 ")); // 123// parseInt() looks for whole numbers at the startconsole.log(parseInt("42")); // 42console.log(parseInt("42px")); // 42 (stops at 'p')console.log(parseInt("px42")); // NaN (starts with non-number)
// Unary plus (+) is a quick way to convert to a numberconsole.log(+"42"); // 42console.log(+"42px"); // NaNconsole.log(+" 123 "); // 123// String() converts any value to its string representationconsole.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.
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.
1<input type="number" id="ageInput" value="25">
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.
1let ageString = document.getElementById('ageInput').value;2console.log(ageString, typeof ageString); // Example: "25" 'string'
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.
1let ageNumber = Number(ageString); // Explicitly convert to number2let nextYearAge = ageNumber + 1;3console.log(nextYearAge, typeof nextYearAge); // Example: 26 'number'
Use the Number
Now you can use ageNumber in calculations or comparisons. This is a crucial step for working with user data.
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 Value | Converts to Number | Converts to Boolean | Converts 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
What is the result of "10" + 5 in JavaScript?
Which of these values is considered 'falsy' when converted to a boolean?
What will Number("20 apples") return?
How can you explicitly convert the string "3.14" to a floating-point number?
Quick Reference
Quick Reference
- 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(), orBoolean(). - 4
Number()— Converts a value strictly to a number; returnsNaNif it can't convert the whole value. - 5
parseInt()/parseFloat()— Extracts a number from the beginning of a string, stopping at the first non-numeric character. - 6
String()— Converts any value into its string representation. - 7
Boolean()— Converts any value totrueorfalse;0,'',null,undefined,NaN, andfalseare falsy. - 8Unary Plus (
+) — A shortcut to convert a value to a number, e.g.,+"5"becomes5. - 9Subtraction (
-) — Forces operands to numbers if possible, e.g.,"10" - "5"becomes5. - 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.