javascript

String(), Number(), Boolean()

Learn how to use JavaScript's String(), Number(), and Boolean() functions for explicit type conversion. Understand why and how to change data types safely.

11 min read 8 sections Tutorial
Share

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?

Getting Started

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.

javascript
1// Start with a number
2let myNumber = 123;
3console.log(typeof myNumber); // Shows 'number'
4
5// Convert the number to a string
6let myString = String(myNumber);
7console.log(typeof myString); // Shows 'string'
8console.log(myString); // Shows '123' (as text)
9
10// Convert the string back to a number
11let 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.

javascript
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}`);
5
6let isActive = true;
7let statusAsString = String(isActive); // true becomes "true"
8console.log(`Status as string: ${statusAsString}, Type: ${typeof statusAsString}`);
9
10let emptyValue = null;
11let nullAsString = String(emptyValue); // null becomes "null"
12console.log(`Null as string: ${nullAsString}, Type: ${typeof nullAsString}`);
13
14// --- Using Number() to convert to a number ---
15let priceText = "99.99";
16let priceNumber = Number(priceText); // "99.99" becomes 99.99
17console.log(`Price as number: ${priceNumber}, Type: ${typeof priceNumber}`);
18
19let isLogged = false;
20let isLoggedNumber = Number(isLogged); // false becomes 0
21console.log(`Logged as number: ${isLoggedNumber}, Type: ${typeof isLoggedNumber}`);
22
23let invalidNumberText = "hello";
24let invalidNumber = Number(invalidNumberText); // "hello" cannot be a number, becomes NaN
25console.log(`Invalid number: ${invalidNumber}, Type: ${typeof invalidNumber}`);
26
27// --- Using Boolean() to convert to true/false ---
28let hasItems = 5;
29let hasItemsBoolean = Boolean(hasItems); // 5 is a 'truthy' value, becomes true
30console.log(`Has items boolean: ${hasItemsBoolean}, Type: ${typeof hasItemsBoolean}`);
31
32let emptyName = "";
33let emptyNameBoolean = Boolean(emptyName); // "" is a 'falsy' value, becomes false
34console.log(`Empty name boolean: ${emptyNameBoolean}, Type: ${typeof emptyNameBoolean}`);
35
36let zero = 0;
37let zeroBoolean = Boolean(zero); // 0 is a 'falsy' value, becomes false
38console.log(`Zero boolean: ${zeroBoolean}, Type: ${typeof zeroBoolean}`);
✗ BadWrong (Implicit Conversion)
let quantity = "5";
let total = quantity + 10; // JavaScript converts 10 to a string
console.log(total); // Output: "510" (a string, not 15)
✓ GoodCorrect (Explicit Conversion)
let quantity = "5";
let total = Number(quantity) + 10; // Convert quantity to a number first
console.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.

Using String()
let myNum = 123;
let result1 = String(myNum); // Converts 123 to "123"
console.log(result1);
VS
Using .toString() Method
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);
Using Number()
let myText = "456";
let result1 = Number(myText); // Converts "456" to 456
console.log(result1);
let mixedText = "100px";
let result2 = Number(mixedText); // Converts "100px" to NaN
console.log(result2);
VS
Using parseInt() / parseFloat()
let myText = "456";
let result3 = parseInt(myText); // Converts "456" to 456
console.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.14
console.log(result5);
Using Boolean()
let value1 = 1;
let result1 = Boolean(value1); // Converts 1 to true
console.log(result1);
let value2 = "hello";
let result2 = Boolean(value2); // Converts "hello" to true
console.log(result2);
VS
Using Double Negation (!!)
let value1 = 1;
let result3 = !!value1; // Converts 1 to true
console.log(result3);
let value2 = "hello";
let result4 = !!value2; // Converts "hello" to true
console.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.

1

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.

javascript
1const inputElement = { value: "150" }; // Imagine this is from a web form
2let userWeightString = inputElement.value;
3console.log(`User input: ${userWeightString}, Type: ${typeof userWeightString}`);
2

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).

javascript
1const inputElement = { value: "150" };
2let userWeightString = inputElement.value;
3let userWeightNumber = Number(userWeightString); // Convert "150" to 150
4console.log(`Converted weight: ${userWeightNumber}, Type: ${typeof userWeightNumber}`);
3

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.

javascript
1const inputElement = { value: "150" };
2let userWeightNumber = Number(inputElement.value);
3const conversionFactor = 0.453592; // 1 pound = 0.453592 kilograms
4let userWeightKg = userWeightNumber * conversionFactor;
5console.log(`Weight in KG: ${userWeightKg.toFixed(2)}`); // Show with 2 decimal places
4

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.

javascript
1const userWeightKg = 68.04; // Our calculated weight
2let 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 ValueString(value)Number(value)Boolean(value)
5"5"5true
"123""123"123true
"hello""hello"NaNtrue
true"true"1true
false"false"0false
null"null"0false
undefined"undefined"NaNfalse
0"0"0false
""""0false
[]""0true
{}"[object Object]"NaNtrue

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

What will typeof String(123) return?

Quick Check

Which of these will result in true when converted using Boolean()?

Quick Check

If let price = "25.50";, what is the result of Number(price) + 10?

Quick Check

What is the primary purpose of using String(), Number(), and Boolean() for type conversion?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 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().
  • 3String(value) — Converts any value into its string representation, e.g., String(123) becomes "123".
  • 4Number(value) — Converts any value into a number, e.g., Number("42") becomes 42. If it cannot convert, it returns NaN.
  • 5Boolean(value) — Converts any value into true or false. 'Falsy' values (0, "", null, undefined, NaN, false) become false, all others become true.
  • 6NaN (Not-a-Number) — This special value means a mathematical operation or number conversion failed, e.g., Number("hello") results in NaN.
  • 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.

Continue Learning