• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Basics / The JavaScript function Math.abs()

The JavaScript function Math.abs()

The JavaScript function Math.abs()

The JavaScript function Math.abs() is a built-in function that returns the absolute value of a number. The absolute value of a number is its distance from zero, regardless of whether the number is positive or negative.

Here is an example of how to use the Math.abs() function:

let num1 = -5;
let num2 = 5;

console.log(Math.abs(num1));  // Output: 5
console.log(Math.abs(num2));  // Output: 5

In the above example, num1 is assigned the value of -5 and num2 is assigned the value of 5. When the Math.abs() function is called on these variables, it returns the absolute value of each number, which is 5 in both cases.

You can also use the Math.abs() function on decimal numbers:

let num3 = -3.14;
let num4 = 3.14;

console.log(Math.abs(num3));  // Output: 3.14
console.log(Math.abs(num4));  // Output: 3.14

As you can see, the Math.abs() function works the same way on decimal numbers as it does on whole numbers.

It is also worth noting that the Math.abs() function does not modify the original variable and returns a new value.

The Math.abs() function can be useful in a variety of situations, such as when you need to determine the distance between two points on a coordinate plane or when you need to calculate the magnitude of a vector.

In short, the JavaScript function Math.abs() returns the absolute value of a number, regardless of whether it is positive or negative. It can be used on both whole numbers and decimal numbers and is a useful tool for a variety of mathematical calculations.

Basics, Math Related

Related Snippets:

  • Bitwise Operators in JavaScript
  • What JavaScript Closures Are and How They Work
  • JavaScript Booleans Explained
  • How To Automatically Redirect To Another URL (JavaScript and jQuery)

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers