# How to find absolute value of a number in JavaScript?

In this article, we will learn **how to find absolute value of a number in JavaScript**?

Submitted by Abhishek Pathak, on October 27, 2017

Working with Mathematics in JavaScript in a lot of fun because of the methods that this language provides. JavaScript has wide range of methods available for almost all sort of Mathematic operations, ranging from power functions to trigonometric and logarithmic functions.

One such method that **JavaScript provides is to find the absolute value of a number**. **The absolute value of a number is a scalar quantity that represents only the value, not the direction. Direction here means, negative and positive**. Suppose, **the absolute value of 3 is 3**, which is same as absolute value of **-3**.

We have the Math.abs() function which returns the absolute value of the number passed to it. This abs() method is the function inside the Math object which is an inbuilt object that JavaScript provides for Mathematical operations. **Here is an example**,

**Code**

var n1 = 10; var n2 = -10; var abs_n1 = Math.abs(n1); var abs_n2 = Math.abs(n2); console.log(abs_n1); // 10 console.log(abs_n2); // 10

As we can see, we have only the value of the number 10, which is same for both -10 and +10. This was done through the JavaScript inbuilt methods. Let us create and define our own absolute function in JavaScript.

**Code**

function absolute(n) { if(n>=0) return n; else return n * (-1); } console.log(absolute(-20)); // 20 console.log(absolute(20)); // 20

In this function, we check if number is greater than equal to 0. If so, we can simply return this value as it itself denotes the scalar value. Else if the number is negative, we multiply it by -1 to change its sign.

That was not too tough. Share your thoughts in the comments below.

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.