• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • JS Introduction
  • JS Getting Started
  • JS Syntax
  • JS Variables
  • JS Generating Output
  • JS Data Types
  • JS Operators
  • JS Events
  • JS Strings
  • JS Numbers
  • JS If Else
  • JS Switch Case
  • JS Arrays
  • JS Sorting Arrays
  • JS Loops
  • JS Functions
  • JS Objects
  • JS DOM Nodes
  • JS DOM Selectors
  • JS DOM Styling
  • JS DOM Get Set Attributes
  • JS DOM Manipulation
  • JS DOM Navigation
  • JS Window
  • JS Screen
  • JS Location
  • JS History
  • JS Navigator
  • JS Dialog Boxes
  • JS Timers
  • JS Date and Time
  • JS Math Operations
  • JS Type Conversions
  • JS Event Listeners
  • JS Event Propagation
  • JS Borrowing Methods
  • JS Hoisting Behavior
  • JS Closures
  • JS Strict Mode
  • JS JSON Parsing
  • JS Error Handling
  • JS Regular Expressions
  • JS Form Validation
  • JS Cookies
  • JS AJAX Requests
  • JS ES6 Features
Home >> javascript >> JS Math Operations

JS Math Operations

Welcome to another tutorial, here you will learn how to perform math operations in JavaScript.

 

Using the Math Object

In JavaScript, the Math object provides a number of useful methods and properties for performing mathematical tasks, such as generating random numbers, rounding numbers, obtaining values such as PI, performing a calculation, etc. It also consists of methods employed in carrying out a mathematical task that is normally impossible or too complex to perform using standard mathematical operators (e.g +, -,*, and /) such as calculating sine or cosine values.

 

The Math.PI Property

The property Math.PI represents the ratio of the circumference of a circle to its diameter. The PI (π) is a mathematical constant, which is approximately 3.14159; i.e Math.PI = π ≈ 3.14159.

Below is an example that calculates the area of a circle using Math.PI property:

// Printing PI value
document.write(Math.PI);  // Prints: 3.141592653589793
 
// Function to calculate circle area
function calculateCircleArea(radius){
    var area = (Math.PI) * radius * radius;
    return area;
}
 
document.write(calculateCircleArea(5));  // Prints: 78.53981633974483
document.write(calculateCircleArea(10));  // Prints: 314.1592653589793

Try with example

Note: In JavaScript, the Math object is a built-in object, so its properties and methods can be accessed directly. Therefore, You don’t need to create a Math object while programming, because it is automatically created by the JavaScript interpreter.

 

Getting the Absolute Value

To calculate the absolute (or positive) value of the number the Math.abs() method is used. For example; -1 is returned as 1, -5 as 5, and so on. It is demonstrated in the example:

document.write(Math.abs(-1));  // Prints: 1
document.write(Math.abs(1));  // Prints: 1
document.write(Math.abs(-5));  // Prints: 5
document.write(Math.abs(-10.5));  // Prints: 10.5

Try with example

 

Generating a Random Number

In JavaScript, the Math.random() method is used to generate a floating-point random number in the range from 0 inclusive up to but not including 1. But, when you need a random integer between zero and an integer higher than one, you could use the solution below:

document.write(Math.random());  // Expected output: a number between 0 and 1
 
// Function to create random integer 
function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}
 
document.write(getRandomInt(3));  // Expected output: 0, 1 or 2
document.write(getRandomInt(1));  // Expected output: 0

Try with example

 

Calculating the Square Root of a Number

To calculate the square root of a number the Math.sqrt() method is used; e.g Math.sqrt(x) = x. But, if the number is negative, NaN is returned. this is an example:

document.write(Math.sqrt(4));  // Prints: 2
document.write(Math.sqrt(16));  // Prints: 4
document.write(Math.sqrt(0.25));  // Prints: 0.5
document.write(Math.sqrt(-9));  // Prints: NaN
 
/* Function to calculate hypotenuse.
Hypotenuse is the longest side of a right-angled triangle. */
function calculateHypotenuse(a, b) {
    return Math.sqrt((a * a) + (b * b));
}
 
document.write(calculateHypotenuse(3, 4));  // Prints: 5
document.write(calculateHypotenuse(5, 12));  // Prints: 13

Try with example

 

Rounding Numbers

In JavaScript, the Math object provides a few methods to round numbers, each one has its purpose. Subsequent sections in this tutorial will describe these methods in details.

The ceil() Method

The Math.ceil() method can be used to round a number up to the next highest integer. For instance, 3.5 becomes 4, -5.7 becomes -5 (because -5 is greater than -6). Below is an example:

document.write(Math.ceil(3.5));  // Prints: 4
document.write(Math.ceil(-5.7));  // Prints: -5
document.write(Math.ceil(9.99));  // Prints: 10
document.write(Math.ceil(-9.99));  // Prints: -9
document.write(Math.ceil(0));  // Prints: 0

Try with example

 

The floor() Method

The Math.floor() method can be used to round a number down to the next lowest integer. For instance, 3.5 becomes 3, -5.7 becomes -6 (because -6 is lesser than -5). Below is an example:

document.write(Math.floor(3.5));  // Prints: 3
document.write(Math.floor(-5.7));  // Prints: -6
document.write(Math.floor(9.99));  // Prints: 9
document.write(Math.floor(-9.99));  // Prints: -10
document.write(Math.floor(0));  // Prints: 0

Try with example

 

The round() Method

The Math.round() method can be used to round a number to the nearest integer in a way that if the decimal part is ‘.5’ or greater, the number is rounded up, otherwise rounded down; as such, 3.5 becomes 4, -5.7 becomes -6, 4.49 becomes 4, etc. below is an example:

document.write(Math.round(3.5));  // Prints: 4
document.write(Math.round(-5.7));  // Prints: -6
document.write(Math.round(7.25));  // Prints: 7
document.write(Math.round(4.49));  // Prints: 4
document.write(Math.round(0));  // Prints: 0

Try with example

 

Finding the Largest and Smallest Numbers

In JavaScript, the largest or smallest can be found in a group of numbers by using the Math.max() and Math.min() methods, respectively. below is an example:

document.write(Math.max(1, 3, 2));  // Prints: 3
document.write(Math.max(-1, -3, -2));  // Prints: -1
 
document.write(Math.min(1, 3, 2));  // Prints: 1
document.write(Math.min(-1, -3, -2));  // Prints: -3

Try with example

 

With the apply() method, you can also find the maximum or minimum value within an array or an array-like object, this is shown in the example below:

var numbers = [1, 3, 2];
 
document.write(Math.max.apply(null, numbers));  // Prints: 3
document.write(Math.min.apply(null, numbers));  // Prints: 1

Try with example

 

There is an even simpler way to do this, by using the ECMAScript 6. Here, you can accomplish the same thing using the new spread operator (...), as shown in the example below:

var numbers = [1, 3, 2];
 
document.write(Math.max(...numbers));  // Prints: 3
document.write(Math.min(...numbers));  // Prints: 1

Try with example

 

Raising Numbers to a Power

To raise a number to a specified power the Math.pow() method is used. The expression Math.pow(x, y) is equivalent to mathematically xy; it shows how many times the base x is multiplied by the exponent y. This is an example:

document.write(Math.pow(3, 2));  // Prints: 9
document.write(Math.pow(0, 1));  // Prints: 0
document.write(Math.pow(5, -2));  // Prints: 0.04
document.write(Math.pow(16, 0.5));  // Prints: 4 (square root of 4)
document.write(Math.pow(8, 1/3));  // Prints: 2 (cube root of 8)

Try with example

Note: Here, a positive exponent indicates multiplication (52 = 5 x 5 = 25), a negative exponent indicates division (5-2 = 1/52 = 0.04), and a fractional exponent indicates a root of the base.

 

Performing Trigonometric Operations

In JavaScript, the Math object also provides numerous trigonometric methods such as sin(), cos(), tan() to perform trigonometric operations. But, this method works in radians, therefore, you have to multiply any degree measurements by π/180 before using them.

Note: Pi radians are equal to 180 degrees: i.e. π rad = 180°. so, π/2 radians = 90°, π/3 radians = 60°, and so on. An example is shown below:

document.write(Math.sin(0 * Math.PI / 180));  // Prints: 0
document.write(Math.sin(90 * Math.PI / 180));  // Prints: 1
document.write(Math.cos(0 * Math.PI / 180));  // Prints: 1
document.write(Math.cos(180 * Math.PI / 180));  // Prints: -1
document.write(Math.tan(0 * Math.PI / 180));  // Prints: 0

Try with example

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.