In JavaScript, data comes in different types, like text (strings), numbers, or true/false values (booleans). Sometimes you need to change a value from one type to another. This is called type conversion. You will learn about the `String()`, `Number()`, and `Boolean()` functions, which help you do this conversion on purpose.
String(), Number(), Boolean()
String(), Number(), Boolean()
In JavaScript, data comes in different types. For example, some data is text, some is a number, and some is just true or false. Sometimes, your program needs a value to be a specific type. For instance, you might get a number as text, but you need to do math with it. This is where type conversion helps. We will learn how to use String(), Number(), and Boolean() to change data types exactly when you want to.
What is Type Conversion?
Type conversion is when you change a value from one data type to another, like turning a number into a string of text, or text into a number.
Explicit Conversion
These functions convert types when you specifically tell JavaScript to do so. This makes your code clear.
Avoid Errors
Converting types correctly helps prevent unexpected errors in your programs, especially with math or comparisons.
Data Handling
Use these functions to prepare data from user input or other sources for calculations and display.
Clarity & Control
Knowing these functions gives you full control over your data types, making your code easier to understand.
What is Type Conversion?
What is Type Conversion?
Imagine you have a number, like 10. If you treat it as text, it's like the word "ten". If you treat it as a number, you can add 5 to it to get 15. JavaScript needs to know if you mean the word or the actual number. Type conversion lets you tell JavaScript exactly what you mean. This is important because different data types behave differently in your code.
1// Start with a number2let myNumber = 123;3console.log(typeof myNumber); // Shows 'number'45// Convert the number to a string6let myString = String(myNumber);7console.log(typeof myString); // Shows 'string'8console.log(myString); // Shows '123' (as text)910// Convert the string back to a number11let convertedNumber = Number(myString);12console.log(typeof convertedNumber); // Shows 'number'13console.log(convertedNumber); // Shows 123 (as a real number)
Watch Out for Implicit Conversion!
Sometimes JavaScript converts types automatically without you asking. This is called implicit conversion. For example, "10" + 5 becomes "105" (a string), not 15. Using String(), Number(), Boolean() makes your intention clear and avoids surprises.
How String(), Number(), and Boolean() Work
How String(), Number(), and Boolean() Work
These three functions are global functions in JavaScript. This means you can use them anywhere in your code. They take almost any value you give them and try to turn it into a string, number, or boolean. They are very direct about their job. They are the main tools for explicit type conversion, meaning you are explicitly asking for the conversion to happen.
1// --- Using String() to convert to text ---2let age = 30;3let ageAsString = String(age); // 30 becomes "30"4console.log(`Age as string: ${ageAsString}, Type: ${typeof ageAsString}`);56let isActive = true;7let statusAsString = String(isActive); // true becomes "true"8console.log(`Status as string: ${statusAsString}, Type: ${typeof statusAsString}`);910let emptyValue = null;11let nullAsString = String(emptyValue); // null becomes "null"12console.log(`Null as string: ${nullAsString}, Type: ${typeof nullAsString}`);1314// --- Using Number() to convert to a number ---15let priceText = "99.99";16let priceNumber = Number(priceText); // "99.99" becomes 99.9917console.log(`Price as number: ${priceNumber}, Type: ${typeof priceNumber}`);1819let isLogged = false;20let isLoggedNumber = Number(isLogged); // false becomes 021console.log(`Logged as number: ${isLoggedNumber}, Type: ${typeof isLoggedNumber}`);2223let invalidNumberText = "hello";24let invalidNumber = Number(invalidNumberText); // "hello" cannot be a number, becomes NaN25console.log(`Invalid number: ${invalidNumber}, Type: ${typeof invalidNumber}`);2627// --- Using Boolean() to convert to true/false ---28let hasItems = 5;29let hasItemsBoolean = Boolean(hasItems); // 5 is a 'truthy' value, becomes true30console.log(`Has items boolean: ${hasItemsBoolean}, Type: ${typeof hasItemsBoolean}`);3132let emptyName = "";33let emptyNameBoolean = Boolean(emptyName); // "" is a 'falsy' value, becomes false34console.log(`Empty name boolean: ${emptyNameBoolean}, Type: ${typeof emptyNameBoolean}`);3536let zero = 0;37let zeroBoolean = Boolean(zero); // 0 is a 'falsy' value, becomes false38console.log(`Zero boolean: ${zeroBoolean}, Type: ${typeof zeroBoolean}`);
let quantity = "5";let total = quantity + 10; // JavaScript converts 10 to a stringconsole.log(total); // Output: "510" (a string, not 15)
let quantity = "5";let total = Number(quantity) + 10; // Convert quantity to a number firstconsole.log(total); // Output: 15 (a number)
Different Ways to Convert Types
Different Ways to Convert Types
While String(), Number(), and Boolean() are great for explicit conversion, JavaScript offers other ways too. Some methods are specific to certain types, like numbers or objects. Understanding these options helps you pick the best tool for the job. We will look at some common alternatives for each type.
let myNum = 123;let result1 = String(myNum); // Converts 123 to "123"console.log(result1);
let myNum = 123;let result2 = myNum.toString(); // Converts 123 to "123"console.log(result2);let myBool = true;let result3 = myBool.toString(); // Converts true to "true"console.log(result3);
let myNum = 123;let result1 = String(myNum); // Converts 123 to "123"console.log(result1);
let myNum = 123;let result2 = myNum.toString(); // Converts 123 to "123"console.log(result2);let myBool = true;let result3 = myBool.toString(); // Converts true to "true"console.log(result3);
let myText = "456";let result1 = Number(myText); // Converts "456" to 456console.log(result1);let mixedText = "100px";let result2 = Number(mixedText); // Converts "100px" to NaNconsole.log(result2);
let myText = "456";let result3 = parseInt(myText); // Converts "456" to 456console.log(result3);let mixedText = "100px";let result4 = parseInt(mixedText); // Converts "100px" to 100 (ignores 'px')console.log(result4);let decimalText = "3.14";let result5 = parseFloat(decimalText); // Converts "3.14" to 3.14console.log(result5);
let myText = "456";let result1 = Number(myText); // Converts "456" to 456console.log(result1);let mixedText = "100px";let result2 = Number(mixedText); // Converts "100px" to NaNconsole.log(result2);
let myText = "456";let result3 = parseInt(myText); // Converts "456" to 456console.log(result3);let mixedText = "100px";let result4 = parseInt(mixedText); // Converts "100px" to 100 (ignores 'px')console.log(result4);let decimalText = "3.14";let result5 = parseFloat(decimalText); // Converts "3.14" to 3.14console.log(result5);
let value1 = 1;let result1 = Boolean(value1); // Converts 1 to trueconsole.log(result1);let value2 = "hello";let result2 = Boolean(value2); // Converts "hello" to trueconsole.log(result2);
let value1 = 1;let result3 = !!value1; // Converts 1 to trueconsole.log(result3);let value2 = "hello";let result4 = !!value2; // Converts "hello" to trueconsole.log(result4);
let value1 = 1;let result1 = Boolean(value1); // Converts 1 to trueconsole.log(result1);let value2 = "hello";let result2 = Boolean(value2); // Converts "hello" to trueconsole.log(result2);
let value1 = 1;let result3 = !!value1; // Converts 1 to trueconsole.log(result3);let value2 = "hello";let result4 = !!value2; // Converts "hello" to trueconsole.log(result4);
When to Choose Which Method
Use String(), Number(), Boolean() when you need a general, explicit conversion for almost any type. Use .toString() if you are sure the value is not null or undefined. Use parseInt()/parseFloat() when you expect a number at the beginning of a string, even if there's other text after it. Use !! for a quick boolean check, but Boolean() is clearer for beginners.
Real-World Use Cases
Real-World Use Cases
Type conversion is not just for theory; it's used all the time in real web projects. When users type information into a form, it often comes into JavaScript as text (a string). If you want to do math with that input, you must convert it to a number. Similarly, you might need to convert true/false values or numbers into text to display them on a webpage. This process ensures your application handles data correctly.
Get User Input from a Form
When a user types something into an input field on a webpage, JavaScript gets that value as a string. Even if they type '10', it's the string "10", not the number 10.
1const inputElement = { value: "150" }; // Imagine this is from a web form2let userWeightString = inputElement.value;3console.log(`User input: ${userWeightString}, Type: ${typeof userWeightString}`);
Convert Input to a Number
If you want to do math with the user's input, you must convert the string to a number. Use Number() for this. If the string cannot be fully converted to a number, Number() will return NaN (Not-a-Number).
1const inputElement = { value: "150" };2let userWeightString = inputElement.value;3let userWeightNumber = Number(userWeightString); // Convert "150" to 1504console.log(`Converted weight: ${userWeightNumber}, Type: ${typeof userWeightNumber}`);
Perform Calculations
Now that you have a real number, you can do mathematical operations with it. For example, you can calculate a weight in kilograms if the input was in pounds.
1const inputElement = { value: "150" };2let userWeightNumber = Number(inputElement.value);3const conversionFactor = 0.453592; // 1 pound = 0.453592 kilograms4let userWeightKg = userWeightNumber * conversionFactor;5console.log(`Weight in KG: ${userWeightKg.toFixed(2)}`); // Show with 2 decimal places
Convert Result Back to String for Display
Often, you want to show the calculated result back to the user on the webpage. To put a number into text content, it's good practice to convert it back to a string using String(). This ensures it blends perfectly with other text.
1const userWeightKg = 68.04; // Our calculated weight2let displayMessage = "Your weight in kilograms is: " + String(userWeightKg.toFixed(2));3console.log(displayMessage); // Output: "Your weight in kilograms is: 68.04"
Mistake: Not Converting User Input
If you forget to convert user input from a string to a number before doing math, JavaScript will try to combine the strings instead of adding numbers. For example, if input1 is "10" and input2 is "5", then input1 + input2 will result in "105" instead of 15. This can lead to very confusing bugs in your application.
Conversion Rules and Edge Cases
Conversion Rules and Edge Cases
Each conversion function has specific rules for how it handles different types of input. It's important to know what to expect, especially for values like null, undefined, empty strings, or objects. Understanding these rules helps you predict how your code will behave and avoid unexpected results. Let's look at a table showing common conversions.
| Input Value | String(value) | Number(value) | Boolean(value) |
|---|---|---|---|
| 5 | "5" | 5 | true |
| "123" | "123" | 123 | true |
| "hello" | "hello" | NaN | true |
| true | "true" | 1 | true |
| false | "false" | 0 | false |
| null | "null" | 0 | false |
| undefined | "undefined" | NaN | false |
| 0 | "0" | 0 | false |
| "" | "" | 0 | false |
| [] | "" | 0 | true |
| {} | "[object Object]" | NaN | true |
Test Your Knowledge
Test Your Knowledge
What will typeof String(123) return?
Which of these will result in true when converted using Boolean()?
If let price = "25.50";, what is the result of Number(price) + 10?
What is the primary purpose of using String(), Number(), and Boolean() for type conversion?
Quick Reference
Quick Reference
- 1Type Conversion — Changing a value from one data type to another, like a string to a number.
- 2Explicit Conversion — When you deliberately tell JavaScript to change a type, using functions like
String(),Number(),Boolean(). - 3
String(value)— Converts anyvalueinto its string representation, e.g.,String(123)becomes"123". - 4
Number(value)— Converts anyvalueinto a number, e.g.,Number("42")becomes42. If it cannot convert, it returnsNaN. - 5
Boolean(value)— Converts anyvalueintotrueorfalse. 'Falsy' values (0, "", null, undefined, NaN, false) becomefalse, all others becometrue. - 6
NaN(Not-a-Number) — This special value means a mathematical operation or number conversion failed, e.g.,Number("hello")results inNaN. - 7User Input — Data from HTML forms is always received as strings; always convert it to a number if you plan to do math.
- 8Clarity — Using these explicit conversion functions makes your code easier to read and understand for yourself and others.
- 9Avoiding Bugs — Proper type conversion prevents unexpected behaviors, especially when mixing data types in operations like addition.
- 10Alternatives — Other methods like
.toString(),parseInt(),parseFloat(), and!!exist for specific conversion needs.
Learn `parseInt()` and `parseFloat()`
Explore how these functions extract numbers from strings, even if they contain other characters.
Understand `isNaN()`
Learn how to check if a value is NaN to handle invalid number conversions gracefully.
Explore Implicit Conversion
Dive deeper into how JavaScript automatically converts types in different operations.
JavaScript Data Types
Review all primitive and object data types in JavaScript to build a strong foundation.
You've Mastered Explicit Type Conversion!
Great job! You now understand how to use String(), Number(), and Boolean() to control data types in your JavaScript code. This skill is super important for writing reliable programs that handle user input and different data sources correctly. Keep practicing, and your code will be much clearer and more robust!
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.