- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Title
- Type conversion
- While loop
JAVASCRIPT
JavaScript Numbers: Syntax, Usage, and Examples
In JavaScript, the Number
type is used to represent both integers and floating-point values. Whether you're counting points in a game or calculating interest, numbers in JavaScript form the foundation of any numerical logic.
How to Use Numbers in JavaScript
The syntax for using numbers in JavaScript is simple. You can assign them directly to variables, use them in expressions, or pass them to functions.
const score = 42;
console.log(score);
JavaScript treats whole numbers (like 42
) and decimal numbers (like 3.14
) the same way—both are instances of the Number
type.
const pi = 3.14159;
const temperature = -5;
const height = 1.75;
You can also use scientific notation:
const large = 1.5e6; // 1.5 million
const small = 2.5e-3; // 0.0025
When to Use Numbers in JavaScript
JavaScript numbers are used anywhere a program needs to store or calculate numeric values. Some typical scenarios include:
Calculations and Math
Numbers are essential when performing basic arithmetic or advanced math.
const total = 100 + 250 - 30 * 2 / 5;
This is useful in financial apps, shopping carts, or anything that requires calculations.
Tracking User Interactions
When building games or interactive apps, you might count clicks, scores, or attempts.
let clickCount = 0;
document.addEventListener("click", () => {
clickCount += 1;
console.log("Clicked:", clickCount);
});
Measuring Time or Animation Progress
You can use numbers to track time intervals, animation durations, or progress values.
const duration = 3000; // in milliseconds
They help manage behaviors like how long a popup appears or how quickly an image fades in.
Examples of Numbers in JavaScript
Let’s look at practical examples of how JavaScript numbers appear in real programs.
1. Score Tracking in a Game
let score = 0;
function addPoints(points) {
score += points;
}
addPoints(10);
console.log(score); // 10
This is a classic case where numbers help track user progress.
2. Discount Calculation in an E-commerce App
const originalPrice = 120;
const discountRate = 0.2;
const discountedPrice = originalPrice * (1 - discountRate);
console.log(discountedPrice); // 96
Here, you use both integers and decimals to compute new prices.
3. Converting Units
const miles = 10;
const kilometers = miles * 1.60934;
console.log(kilometers); // 16.0934
This is a common pattern when building features for travel, fitness, or science apps.
Learn More About JavaScript Numbers
Number Precision and Floating-Point Quirks
JavaScript numbers follow the IEEE 754 standard, which means they can introduce rounding issues with decimals:
console.log(0.1 + 0.2); // 0.30000000000000004
To work around this, you can use rounding methods like toFixed()
or multiply before rounding:
const result = (0.1 + 0.2).toFixed(2); // "0.30"
Common Number Methods
JavaScript provides several helpful methods for working with numbers:
Number.isInteger(value)
checks if a value is an integer.Math.round(num)
rounds to the nearest integer.Math.floor(num)
rounds down.Math.ceil(num)
rounds up.Math.random()
returns a random number between 0 and 1.
Example:
const value = 42.7;
console.log(Math.floor(value)); // 42
console.log(Math.ceil(value)); // 43
Type Coercion and Numbers
JavaScript automatically converts types in some situations:
const result = "5" * 2; // 10 (string gets converted)
const broken = "5px" * 2; // NaN
Use Number()
or parseInt()
to convert strings to numbers intentionally:
const ageString = "25";
const age = Number(ageString); // 25
Special Numeric Values
JavaScript numbers include some special values:
NaN
(Not-a-Number): returned when a math operation fails.Infinity
: returned when a value exceeds the upper limit.Infinity
: returned for the opposite.
Examples:
console.log(5 / 0); // Infinity
console.log("hello" * 2); // NaN
Check for NaN
with Number.isNaN(value)
.
Integers vs. Floating Point
There’s no separate integer type in JavaScript. Whether it’s 1
or 1.0
, it’s all the same under the hood. However, you can check for integer values:
Number.isInteger(10); // true
Number.isInteger(10.5); // false
BigInt for Large Numbers
If you need to store numbers larger than Number.MAX_SAFE_INTEGER
, use BigInt
.
const big = 1234567890123456789012345678901234567890n;
BigInt uses an n
at the end and can handle much larger integers without losing precision.
Working with Decimal Precision
Need exactly two decimal places, like in a receipt? Use toFixed()
:
const total = 19.9876;
console.log(total.toFixed(2)); // "19.99"
Note: toFixed()
returns a string.
Parsing Strings into Numbers
Strings can be converted into numbers using:
Number("42")
→ 42parseInt("42px")
→ 42parseFloat("3.14")
→ 3.14
These conversions are useful when dealing with form input or inline styles.
Checking for Finite Numbers
Sometimes you want to verify that a number is valid and finite:
const input = 100;
console.log(Number.isFinite(input)); // true
Avoid using isFinite()
without the Number.
prefix, it coerces non-numbers.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.