Skip to content

JavaScript negative to positive

  • by

In JavaScript, you can convert a negative number to a positive number using the Math.abs() method, which returns the absolute value of a number. Alternatively, you can also multiply the negative number with -1 or use the bitwise not operator twice to flip the sign of the number.

JavaScript negative to the positive example

Simple several example codes to convert a negative number to a positive number.

Math.abs() method:

The Math.abs() method returns the absolute value of a number, which is the number without considering its sign. Therefore, applying Math.abs() to a negative number will return the positive version of that number.

let num = -10;
let positiveNum = Math.abs(num);
console.log(positiveNum); // Output: 10

Multiplying the negative number with -1:

Another way to convert a negative number to a positive number is to multiply it by -1. This works because when you multiply a negative number by a negative number, you get a positive number.

let num = -10;
let positiveNum = num * -1;
console.log(positiveNum); // Output: 10

Using the bitwise not operator:

You can also use the bitwise not operator (~) twice to convert a negative number to a positive number.

let num = -10;
let positiveNum = ~~num;
console.log(positiveNum); // Output: 10

Another example

Let’s say we have an array of numbers, some of which may be negative, and you want to get the sum of all the positive numbers in the array.


const numbers = [2, -5, 8, 0, -3, 10];

let sum = 0;

for (let i = 0; i < numbers.length; i++) {
    const num = numbers[i];
    // Check if the number is positive
    if (num > 0) {
        // Add the positive number to the sum
        sum += num;
    }
}

console.log("Sum of positive numbers:", sum);

Output:

JavaScript negative to positive

You can modify the condition inside the loop to check whether the number is less than or equal to 0. If it is, you can convert it to a positive number using the Math.abs() method and then add it to the sum variable.

const numbers = [2, -5, 8, 0, -3, 10];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
    const num = numbers[i];
    if (num <= 0) {
        // Convert the negative number to positive and add it to the sum
        sum += Math.abs(num);
    } else {
        // Add the positive number to the sum
        sum += num;
    }
}

console.log("Sum of positive numbers:", sum);

Comment if you have any doubts or suggestions on this Js basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *