How to Returns the absolute value of x in JavaScript ?


In JavaScript, we can return the absolute value of a number using the Math.abs() method. This method returns the absolute value of a number, which is the positive value of the number, regardless of its sign.

Here's an example:

let x = -5;
let absX = Math.abs(x);
console.log(absX); // Output: 5

In this example, we first declare a variable x and assign it a value of -5. We then use the Math.abs() method to get the absolute value of x and assign it to a new variable absX. Finally, we log the value of absX to the console, which outputs 5.

Another way to get the absolute value of a number in JavaScript is by using a conditional statement. We can check if the number is negative and multiply it by -1 to get its positive value. If the number is already positive, we can simply return the number.

Here's an example:

function getAbsoluteValue(x) {
  if (x < 0) {
    return -x;
  } else {
    return x;
  }
}

let absX = getAbsoluteValue(-5);
console.log(absX); // Output: 5

In this example, we define a function getAbsoluteValue that takes a number x as its parameter. We then use a conditional statement to check if x is negative. If it is, we return -x to get its positive value. If x is already positive, we simply return x. We then call the getAbsoluteValue function with a value of -5 and assign its return value to a variable absX. Finally, we log the value of absX to the console, which outputs 5.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.