Mathematical Operators
Learn about mathematical operators
Mathematical Operators
What are mathematical operators?
Mathematical operators perform calculations on numbers. JavaScript supports standard math operations plus some advanced functions in the Math object.
Benefits of mathematical operators?
- Calculate positions in games
- Handle damage calculations
- Manage health and resources
- Create physics simulations
- Process numerical game data
// Basic operations
const health = 100;
const damage = 20;
const newHealth = health - damage; // Subtraction
const sum = 5 + 10; // 2 (addition)
const product = 5 * 10; // 50 (multiplication)
const quotient = 10 / 2; // 5 (division)
// Modulo (remainder)
const remainder = 17 % 5; // 2
// Exponentiation
const squared = 5 ** 2; // 25
// Math object
const max = Math.max(10, 20, 30); // 30
const random = Math.random(); // 0 to 1
const rounded = Math.round(4.7); // 5
const absolute = Math.abs(-10); // 10
What does this code do?
- Uses basic operators:
-for subtraction - Uses
%modulo operator to get remainder - Uses
**exponentiation operator for powers - Uses
Math.max()to find largest number - Uses
Math.random()to generate random number - Uses
Math.round()to round decimals - Uses
Math.abs()to get absolute value
Try It Yourself
%%js // CODE_RUNNER: mathematical const damage = 25; const health = 100; const newHealth = Math.max(0, health - damage); console.log(newHealth); const random = Math.floor(Math.random() * 100); console.log(“Random: “ + random); console.log(“Square root of 16: “ + Math.sqrt(16));