How to Negate All Numbers in a JavaScript Array?

In JavaScript, you can negate all numbers in an array of numbers by applying the unary negation operator (-) on every element of the array using Array.prototype.map(), for example, like so:

// ES6+
const arr = [3, 2, -1, 0, 4, -6, -5];
const newArr = arr.map((num) => -num);

console.log(newArr); // [-3, -2, 1, -0, -4, 6, 5]

You can rewrite the callback to Array.prototype.map() without arrow function to make it compatible with ES5.

The code above would create a new array with all numbers in the array negated (i.e. positive numbers will be flipped to negative and negative numbers will be converted to positive). You can achieve the same with a simple for loop as well:

const arr = [3, 2, -1, 0, 4, -6, -5];
const newArr = [];

for (let i = 0; i < arr.length; i++) {
    newArr.push(-arr[i]);
}

console.log(newArr); // [-3, -2, 1, -0, -4, 6, 5]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.