Numbers and Math
JavaScript provides support for numeric data types, allowing you to perform various mathematical operations. In this section, we'll explore numbers, mathematical operations, and the Math
object.
1. Numbers in JavaScript
In JavaScript, you can work with different types of numbers, including integers and floating-point numbers. Numbers are used for various calculations and mathematical operations in your code.
let integerNumber = 42;
let floatingPointNumber = 3.14;
2. Basic Mathematical Operations
JavaScript supports the standard mathematical operations, including addition, subtraction, multiplication, division, and modulus.
let sum = 10 + 5; // Addition
let difference = 20 - 8; // Subtraction
let product = 7 * 3; // Multiplication
let quotient = 15 / 5; // Division
let remainder = 11 % 3; // Modulus (remainder of division)
3. Math Object
JavaScript provides the Math
object, which offers a wide range of mathematical functions and constants. Here are some common methods and properties:
-
Math.PI
: The mathematical constant Pi (π). -
Math.abs(x)
: Returns the absolute value of a number. -
Math.round(x)
: Rounds a number to the nearest integer. -
Math.floor(x)
: Rounds a number down to the nearest integer. -
Math.ceil(x)
: Rounds a number up to the nearest integer. -
Math.max(x, y, ...)
: Returns the largest of the given numbers. -
Math.min(x, y, ...)
: Returns the smallest of the given numbers. -
Math.pow(x, y)
: Returnsx
to the power ofy
. -
Math.sqrt(x)
: Returns the square root of a number. -
Math.random()
: Returns a random floating-point number between 0 (inclusive) and 1 (exclusive).
let radius = 5;
let circumference = 2 * Math.PI * radius;
let squared = Math.pow(4, 2);
let randomNumber = Math.random(); // Random number between 0 and 1
4. NaN (Not-a-Number)
NaN
is a special value in JavaScript that represents the result of an invalid or undefined mathematical operation. It is often used to indicate that a value is not a valid number.
let result = 'Hello' / 2; // Result is NaN
You can check if a value is NaN
using the isNaN()
function.
5. Infinity and -Infinity
JavaScript also provides the values Infinity
and -Infinity
to represent positive and negative infinity. These values are used to represent mathematical concepts, such as division by zero.
let positiveInfinity = Infinity;
let negativeInfinity = -Infinity;
6. Number Conversions
You can convert between different data types and representations of numbers using functions like parseInt()
, parseFloat()
, and the Number()
constructor.
let stringNumber = '42';
let parsedNumber = parseInt(stringNumber); // Converts to an integer
let floatValue = parseFloat('3.14'); // Converts to a float
let numberFromBoolean = Number(true); // Converts a boolean to a number
Understanding numbers and mathematical operations is crucial for various aspects of JavaScript development, from simple calculations to complex mathematical modeling.