Home Web Front-end JS Tutorial JavaScript Math Object Cheatsheet

JavaScript Math Object Cheatsheet

Nov 26, 2024 pm 03:08 PM

JavaScript Math Object Cheatsheet

The Math object in JavaScript provides a set of properties and methods for performing mathematical tasks. Here's a comprehensive cheat sheet for the Math object.


Properties

The Math object has a set of constants:

Property Description Value (Approx.)
Math.E Euler's number 2.718
Math.LN2 Natural logarithm of 2 0.693
Math.LN10 Natural logarithm of 10 2.302
Math.LOG2E Base 2 logarithm of Math.E 1.442
Math.LOG10E Base 10 logarithm of Math.E 0.434
Math.PI Ratio of a circle's circumference to its diameter 3.14159
Math.SQRT1_2 Square root of 1/2 0.707
Math.SQRT2 Square root of 2 1.414

Methods

1. Rounding Methods

Method Description Example
Math.round(x) Rounds to the nearest integer Math.round(4.5) → 5
Math.floor(x) Rounds down to the nearest integer Math.floor(4.7) → 4
Math.ceil(x) Rounds up to the nearest integer Math.ceil(4.1) → 5
Math.trunc(x) Removes the decimal part (truncates) Math.trunc(4.9) → 4

2. Random Number Generation

Method Description Example
Math.random() Generates a random number between 0 and 1 (exclusive) Math.random() → 0.53
Custom Random Int Generator Random integer between min and max Math.floor(Math.random() * (max - min 1)) min

3. Arithmetic Methods

Method Description Example
Math.abs(x) Absolute value Math.abs(-7) → 7
Math.pow(x, y) Raises x to the power of y Math.pow(2, 3) → 8
Math.sqrt(x) Square root of x Math.sqrt(16) → 4
Math.cbrt(x) Cube root of x Math.cbrt(27) → 3
Math.hypot(...values) Square root of the sum of squares of arguments Math.hypot(3, 4) → 5

4. Exponential and Logarithmic Methods

Method Description Example
Math.exp(x) e^x Math.exp(1) → 2.718
Math.log(x) Natural logarithm (ln(x)) Math.log(10) → 2.302
Math.log2(x) Base 2 logarithm of x Math.log2(8) → 3
Math.log10(x) Base 10 logarithm of x Math.log10(100) → 2

5. Trigonometric Methods

Method Description Example
Math.sin(x) Sine of x (x in radians) Math.sin(Math.PI / 2) → 1
Math.cos(x) Cosine of x (x in radians) Math.cos(0) → 1
Math.tan(x) Tangent of x (x in radians) Math.tan(Math.PI / 4) → 1
Math.asin(x) Arcsine of x (returns radians) Math.asin(1) → 1.57
Math.acos(x) Arccosine of x Math.acos(1) → 0
Math.atan(x) Arctangent of x Math.atan(1) → 0.785
Math.atan2(y, x) Arctangent of y / x Math.atan2(1, 1) → 0.785

6. Min, Max, and Clamping

Method Description Example
Math.max(...values) Returns the largest value Math.max(5, 10, 15) → 15
Math.min(...values) Returns the smallest value Math.min(5, 10, 15) → 5
Custom Clamping Restrict a value to a range Math.min(Math.max(x, min), max)

7. Other Methods

Method Description Example
Math.sign(x) Returns 1, -1, or 0 based on sign of x Math.sign(-10) → -1
Math.fround(x) Nearest 32-bit floating-point number Math.fround(5.5) → 5.5
Math.clz32(x) Counts leading zero bits in 32-bit binary Math.clz32(1) → 31

Examples

Random Integer Between 1 and 100

const randomInt = Math.floor(Math.random() * 100) + 1;
console.log(randomInt);
Copy after login

Calculate Circle Area

const radius = 5;
const area = Math.PI * Math.pow(radius, 2);
console.log(area); // 78.54
Copy after login
Copy after login

Convert Degrees to Radians

const degrees = 90;
const radians = degrees * (Math.PI / 180);
console.log(radians); // 1.57
Copy after login

Find the Largest Number in an Array

const nums = [5, 3, 9, 1];
console.log(Math.max(...nums)); // 9
Copy after login

Extended Use Cases for the Math Object

The Math object has many practical applications. Here’s a list of common scenarios and examples to illustrate how to use it effectively.


1. Randomization

Generate a Random Integer Within a Range

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1, 10)); // Random number between 1 and 10
Copy after login

Shuffle an Array

function shuffleArray(arr) {
    return arr.sort(() => Math.random() - 0.5);
}
console.log(shuffleArray([1, 2, 3, 4, 5])); // Shuffled array
Copy after login

Simulate a Dice Roll

function rollDice() {
    return Math.floor(Math.random() * 6) + 1; // Random number between 1 and 6
}
console.log(rollDice());
Copy after login

2. Geometry and Shapes

Calculate the Area of a Circle

const radius = 5;
const area = Math.PI * Math.pow(radius, 2);
console.log(area); // 78.54
Copy after login
Copy after login

Calculate the Hypotenuse of a Triangle

const a = 3, b = 4;
const hypotenuse = Math.hypot(a, b);
console.log(hypotenuse); // 5
Copy after login

Convert Degrees to Radians

function degreesToRadians(degrees) {
    return degrees * (Math.PI / 180);
}
console.log(degreesToRadians(90)); // 1.57
Copy after login

3. Finance and Business

Compound Interest Formula

function compoundInterest(principal, rate, time, n) {
    return principal * Math.pow((1 + rate / n), n * time);
}
console.log(compoundInterest(1000, 0.05, 10, 12)); // 47.01
Copy after login

Rounding Currency Values

const amount = 19.56789;
const rounded = Math.round(amount * 100) / 100; // Round to 2 decimal places
console.log(rounded); // 19.57
Copy after login

Calculate Discounts

function calculateDiscount(price, discount) {
    return Math.floor(price * (1 - discount / 100));
}
console.log(calculateDiscount(200, 15)); // 0
Copy after login

4. Games and Animation

Simulate a Coin Toss

function coinToss() {
    return Math.random() < 0.5 ? 'Heads' : 'Tails';
}
console.log(coinToss());
Copy after login

Easing Functions for Smooth Animations

function easeOutQuad(t) {
    return t * (2 - t); // Simple easing function
}
console.log(easeOutQuad(0.5)); // 0.75
Copy after login

Random Spawning Coordinates in a 2D Grid

function randomCoordinates(gridSize) {
    const x = Math.floor(Math.random() * gridSize);
    const y = Math.floor(Math.random() * gridSize);
    return { x, y };
}
console.log(randomCoordinates(10)); // e.g., {x: 7, y: 2}
Copy after login

5. Data Analysis

Find the Maximum and Minimum in an Array

const scores = [85, 90, 78, 92, 88];
console.log(Math.max(...scores)); // 92
console.log(Math.min(...scores)); // 78
Copy after login

Normalize Data

function normalize(value, min, max) {
    return (value - min) / (max - min);
}
console.log(normalize(75, 0, 100)); // 0.75
Copy after login

6. Physics and Engineering

Calculate Velocity After Free Fall

const gravity = 9.8; // m/s^2
const time = 3; // seconds
const velocity = gravity * time;
console.log(velocity); // 29.4 m/s
Copy after login

Period of a Pendulum

function pendulumPeriod(length) {
    return 2 * Math.PI * Math.sqrt(length / 9.8);
}
console.log(pendulumPeriod(1)); // 2.006 seconds
Copy after login

7. Number Manipulation

Clamp a Number Within a Range

function clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
}
console.log(clamp(15, 10, 20)); // 15
console.log(clamp(5, 10, 20));  // 10
Copy after login

Convert Negative Numbers to Positive

console.log(Math.abs(-42)); // 42
Copy after login

Find the Integer Part of a Number

console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4
Copy after login

8. Problem-Solving

Check if a Number is a Power of 2

function isPowerOfTwo(n) {
    return Math.log2(n) % 1 === 0;
}
console.log(isPowerOfTwo(8)); // true
console.log(isPowerOfTwo(10)); // false
Copy after login

Generate Fibonacci Numbers

function fibonacci(n) {
    const phi = (1 + Math.sqrt(5)) / 2;
    return Math.round((Math.pow(phi, n) - Math.pow(-phi, -n)) / Math.sqrt(5));
}
console.log(fibonacci(10)); // 55
Copy after login

9. Miscellaneous

Generate Random Colors (RGB)

function getRandomColor() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r}, ${g}, ${b})`;
}
console.log(getRandomColor()); // e.g., rgb(123, 45, 67)
Copy after login

Calculate Age from Date of Birth

function calculateAge(birthYear) {
    const currentYear = new Date().getFullYear();
    return currentYear - birthYear;
}
console.log(calculateAge(1990)); // e.g., 34
Copy after login

The above is the detailed content of JavaScript Math Object Cheatsheet. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles