Math.abs ExamplesΒΆ

The general syntax for this method is:

Math.abs(number)

This method returns the positive value of a number, which can be printed or stored in a variable. abs works on both integer and decimal values.

Numerical strings can also be evaluated, but should be avoided as a best practice.

Example

1let num = Math.abs(-3);
2console.log(num);
3
4console.log(Math.abs(4.44));
5console.log(Math.abs('-3.33'));
6
7console.log(Math.abs(24/-3));
8// 24/-3 = -8

Console Output

3
4.44
3.33
8

Math.abs also works on arrays, but to make the process work, we must combine it with the map array method. The syntax for this is:

arrayName.map(Math.abs)

Note that Math.abs takes no argument when applied to an array.

Example

1let numbers = [-2, 3, -4.44, "8.88"];
2
3let positiveArray = numbers.map(Math.abs);
4
5console.log(positiveArray);

Console Output

[2, 3, 4.44, 8.88]