In JavaScript, numbers are a fundamental data type used to represent numerical values, both integers (whole numbers) and floating-point numbers (numbers with decimals).
Unlike some other programming languages, JavaScript doesn't differentiate between integer and floating-point numbers; both are treated as the same data type called Number
.
This means that whether you're working with 5
or 5.5
, JavaScript handles them in the same way. JavaScript also supports very large and very small numbers using scientific notation (e.g., 1e6
for 1 million).
One thing to keep in mind is that JavaScript numbers are based on the IEEE 754 standard, which can sometimes lead to precision issues with floating-point arithmetic.
For example, 0.1 + 0.2
doesn't exactly equal 0.3
due to how these numbers are stored in memory.
Despite this, JavaScript provides a range of built-in methods to work with numbers, such as rounding, converting to integers, and checking for infinity or NaN (Not-a-Number).
10 Example Codes:
Basic Addition:
let sum = 5 + 3; console.log(sum); // Outputs: 8
Subtraction:
let difference = 10 - 4; console.log(difference); // Outputs: 6
Multiplication:
let product = 7 * 6; console.log(product); // Outputs: 42
Division:
let quotient = 20 / 4; console.log(quotient); // Outputs: 5
Modulus (Remainder):
let remainder = 10 % 3; console.log(remainder); // Outputs: 1
Exponentiation:
let power = 2 ** 3; console.log(power); // Outputs: 8
Incrementing a Number:
let count = 0; count++; console.log(count); // Outputs: 1
Decrementing a Number:
let count = 5; count--; console.log(count); // Outputs: 4
Parsing a String to a Number:
let num = parseInt("123"); console.log(num); // Outputs: 123
Checking for NaN:
let notANumber = "abc" / 3; console.log(isNaN(notANumber)); // Outputs: true