Numbers in JavaScript are used to represent both integer and floating-point values. They are fundamental for performing mathematical operations, storing numeric data, and making calculations in programs.
Numbers can be assigned directly to variables
let integerNumber = 42;
let floatingPointNumber = 3.14;
console.log(integerNumber) // 42
console.log(floatingPointNumber) // 3.14
JavaScript supports standard arithmetic operations like addition, subtraction, multiplication, and division.
let sum = 10 + 20; // 30
let difference = 50 - 30; // 20
let product = 5 * 6; // 30
let quotient = 15 / 3; // 5
console.log(sum) // 30
console.log(difference) // 20
console.log(product) // 30
console.log(quotient) // 5
JavaScript's Math object provides a range of mathematical functions and constants
let pi = Math.PI; // 3.141592653589793
let squareRoot = Math.sqrt(16); // 4
let random = Math.random(); // A random number between 0 and 1
console.log(pi) // 3.141592653589793
console.log(squareRoot) // 4
console.log(random) // A random number between 0 and 1
JavaScript provides methods for rounding numbers
let rounded = Math.round(4.5); // 5
let floorValue = Math.floor(4.9); // 4
let ceilValue = Math.ceil(4.1); // 5
console.log(rounded) // 5
console.log(floorValue) // 4
console.log(ceilValue) // 5
JavaScript uses 64-bit floating-point representation, which can result in precision issues for very large or very small numbers. Libraries like BigInt and Decimal.js can help manage precision.
JavaScript has special values for calculations that can't produce a valid result
let result = 0 / 0; // NaN
let positiveInfinity = 1 / 0; // Infinity
let negativeInfinity = -1 / 0; // -Infinity
console.log(result) // NaN
console.log(positiveInfinity) // Infinity
console.log(negativeInfinity) // -Infinity
JavaScript provides several methods for working with numbers
let number = 42.34567;
let numberAsString = number.toString(); // "42.34567"
let fixedNumber = number.toFixed(2); // "42.35"
let precisionNumber = number.toPrecision(4); // "42.35"
let parsedInt = parseInt("42"); // 42
let parsedFloat = parseFloat("42.34567"); // 42.34567
console.log(number) // 42.34567
console.log(numberAsString) // "42.34567"
console.log(fixedNumber) // "42.35"
console.log(precisionNumber) // "42.35"
console.log(parsedInt) // 42
console.log(parsedFloat) // 42.34567
Numbers in JavaScript are fundamental for mathematical operations and calculations. JavaScript provides various methods and functions for working with numbers, including arithmetic operations, mathematical constants, rounding, and precision management.