In JavaScript, a Number is a special type of data that helps your computer understand and work with mathematical values. This tutorial will teach you how to use numbers for counting, measuring, and doing all kinds of math. You will learn how to write numbers, perform calculations, and understand important rules about them.
Number
Number
In JavaScript, a Number is a special type of data that helps your computer understand and work with mathematical values. It is one of the most basic data types you will use. This tutorial will teach you how to use numbers for counting, measuring, and doing all kinds of math. You will learn how to write numbers, perform calculations, and understand important rules about them.
What is a Number?
The Number data type in JavaScript represents both whole numbers (like 10, 500) and decimal numbers (like 3.14, 99.5).
Whole Numbers
Numbers without any decimal points are called integers, like 10, 100, or -5.
Decimal Numbers
Numbers with a decimal point are called floating-point numbers, like 3.14 or 0.5.
Math Operations
You can use numbers to do addition, subtraction, multiplication, and division easily.
Special Values
Numbers also include special values like NaN (Not a Number) and Infinity for special cases.
What is a Number?
What is a Number?
Imagine you want to count how many apples you have or measure the temperature outside. In JavaScript, you use the Number data type for these tasks. Numbers let your computer store and work with quantities. They can be positive, negative, or zero.
1// This is a whole number (an integer)2let score = 100;34// This is a decimal number (a floating-point number)5let price = 19.99;67// You can also use negative numbers8let temperature = -5;910// You can do math with numbers11let totalScore = score + 50; // totalScore will be 15012let finalPrice = price * 2; // finalPrice will be 39.981314console.log("Score:", score); // Shows 10015console.log("Price:", price); // Shows 19.9916console.log("Total Score:", totalScore); // Shows 150
Numbers Without Quotes
Always write numbers without quotes around them. If you put quotes around a number, JavaScript will treat it as a string (text), not a number. This can cause problems when you try to do math!
How Numbers Work
How Numbers Work
JavaScript handles all numbers as a special kind called 'floating-point' numbers. This means even a whole number like 5 is technically stored as 5.0. This is important for doing math that mixes whole numbers and decimals. You can perform all the basic math operations you learned in school.
1let num1 = 10;2let num2 = 3;34// Addition (+)5let sum = num1 + num2; // sum is 136console.log("Sum:", sum);78// Subtraction (-)9let difference = num1 - num2; // difference is 710console.log("Difference:", difference);1112// Multiplication (*)13let product = num1 * num2; // product is 3014console.log("Product:", product);1516// Division (/)17let quotient = num1 / num2; // quotient is 3.333333333333333518console.log("Quotient:", quotient);1920// Modulus (%) - gives the remainder after division21let remainder = num1 % num2; // remainder is 1 (10 divided by 3 is 3 with 1 left over)22console.log("Remainder:", remainder);
let a = "5";let b = "2";let result = a + b; // result is "52" (strings are joined, not added)console.log(result);
let a = 5;let b = 2;let result = a + b; // result is 7 (numbers are added)console.log(result);
Different Ways to Use Numbers
Different Ways to Use Numbers
Sometimes, you might get numbers as text (strings) from a user or a file. Before you can do math with them, you need to turn them into actual Number types. JavaScript has special tools for this. Two common tools are parseInt() and parseFloat().
let textAge = "30";let age = parseInt(textAge); // age is now the number 30console.log(age); // Output: 30console.log(typeof age); // Output: numberlet mixedText = "123pixels";let pixels = parseInt(mixedText); // pixels is 123 (it stops at 'p')console.log(pixels); // Output: 123
let textPrice = "49.99";let price = parseFloat(textPrice); // price is now the number 49.99console.log(price); // Output: 49.99console.log(typeof price); // Output: numberlet mixedMeasurement = "2.5meters";let meters = parseFloat(mixedMeasurement); // meters is 2.5 (stops at 'm')console.log(meters); // Output: 2.5
let textAge = "30";let age = parseInt(textAge); // age is now the number 30console.log(age); // Output: 30console.log(typeof age); // Output: numberlet mixedText = "123pixels";let pixels = parseInt(mixedText); // pixels is 123 (it stops at 'p')console.log(pixels); // Output: 123
let textPrice = "49.99";let price = parseFloat(textPrice); // price is now the number 49.99console.log(price); // Output: 49.99console.log(typeof price); // Output: numberlet mixedMeasurement = "2.5meters";let meters = parseFloat(mixedMeasurement); // meters is 2.5 (stops at 'm')console.log(meters); // Output: 2.5
Choosing parseInt() or parseFloat()
Use parseInt() when you only care about the whole number part and want to ignore any decimals. Use parseFloat() when you need to keep the decimal part of a number. Both functions stop reading the string as soon as they see something that is not a number character.
Numbers in Real Projects
Numbers in Real Projects
Numbers are everywhere in real programming projects. They are used for keeping scores in games, calculating prices in online stores, or tracking measurements in scientific apps. Understanding how to handle numbers correctly is very important. Let's look at a common example: calculating a total price.
Get User Input as Text
Imagine a user types a quantity into a box on a website. This input usually comes as a string (text).
1let quantityText = "3"; // User typed '3'2let itemPrice = 15.50; // This is already a number
Convert Text to a Number
Before you can do math, you must turn the quantityText string into a real Number. We use parseInt() here because quantity is usually a whole number.
1let quantity = parseInt(quantityText); // Converts "3" to the number 32console.log(typeof quantity); // Shows 'number'
Perform Calculations
Now that both quantity and itemPrice are numbers, you can safely multiply them to get the total.
1let totalPrice = quantity * itemPrice; // 3 * 15.50 = 46.52console.log("Total Price:", totalPrice); // Shows 46.5
Display the Result
Finally, you can show the calculated totalPrice to the user. This is a common pattern for handling numerical data from user interfaces.
1document.getElementById("result").innerText = "Your total is: $" + totalPrice.toFixed(2); // Shows "Your total is: $46.50"2// .toFixed(2) makes sure it has exactly 2 decimal places, like money
The Danger of Unconverted Strings
If you forget to convert user input from a string to a Number before doing math, you might get unexpected results. For example, '5' + 2 would result in '52' (text joining), not 7 (numerical addition). Always convert before calculating!
Number Properties and Methods
Number Properties and Methods
JavaScript numbers come with some built-in tools called properties and methods. Properties are like special facts about numbers, and methods are like actions numbers can do. These tools help you work with numbers more effectively, especially for formatting or checking their type.
| Property/Method | Description | Example |
|---|---|---|
| `NaN` (Not a Number) | A special value meaning 'Not a Number'. It appears when a math operation fails to produce a real number. | `0 / 0` results in `NaN` |
| `Infinity` | A special value representing a number that is too large to be represented. Also `-Infinity` for very small numbers. | `1 / 0` results in `Infinity` |
| `Number.isNaN()` | Checks if a value is `NaN`. It returns `true` or `false`. | `Number.isNaN(0/0)` is `true` |
| `Number.isFinite()` | Checks if a value is a finite number (not `Infinity` or `NaN`). | `Number.isFinite(100)` is `true` |
| `num.toFixed(digits)` | Formats a number to a string with a specific number of decimal places. | `(3.14159).toFixed(2)` is `"3.14"` |
| `num.toString()` | Converts a number into its string representation. | `(123).toString()` is `"123"` |
Test Your Knowledge
Test Your Knowledge
Which of the following is a valid JavaScript Number?
What will be the result of this JavaScript code: let x = 10; let y = 3; console.log(x % y);?
You have a string "25.75kg". Which function should you use to get the number 25.75?
What does console.log(0 / 0); output in JavaScript?
Quick Reference
Quick Reference
- 1Number Type — JavaScript's
Numberdata type handles both whole numbers (integers) and decimal numbers (floating-point numbers). - 2No Quotes — Always write numbers without quotes around them; quotes make them
stringsinstead ofNumbers. - 3Basic Math — You can perform addition (
+), subtraction (-), multiplication (*), division (/), and modulus (%) with numbers. - 4
parseInt()— UseparseInt()to convert a string to a whole number, stopping at the first non-numeric character. - 5
parseFloat()— UseparseFloat()to convert a string to a decimal number, also stopping at the first non-numeric character. - 6
NaN— This special value means "Not a Number" and occurs when a mathematical operation fails or is invalid (e.g.,0 / 0). - 7
Infinity— This special value represents a number that is too large to be represented, often seen when dividing by zero (e.g.,1 / 0). - 8
toFixed()— ThetoFixed()method helps format numbers to a specific number of decimal places, returning a string. - 9Data Conversion — Always convert string inputs to numbers using
parseInt()orparseFloat()before performing calculations to avoid errors. - 10Floating-Point — Be aware that JavaScript uses floating-point arithmetic, which can sometimes lead to tiny inaccuracies with decimals.
Strings
Learn how to work with text data in JavaScript, which is called a String.
Booleans
Discover the true/false data type essential for making decisions in your code.
Operators
Explore all the symbols and keywords used to perform operations on data.
Math Object
Dive into JavaScript's built-in Math object for more advanced mathematical functions.
Great Job!
You've successfully learned about JavaScript's Number data type! You can now confidently use numbers for math, understand how to convert them, and handle special numerical values. Keep practicing, and you'll master working with numbers in your code!
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.