To subtract all of the numbers of an array in JavaScript, we can use the JavaScript Array **reduce()** method. Here is the setup for how this can be done:

```
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function subtractArray(total, item) {
return total - item;
}
console.log(numbers.reduce(subtractArray));
#Output
-43
```

We can also use a for loop to subtract all of the numbers of an array easily.

```
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var total = numbers[0];
for( var i =1; i<numbers.length; i++ ){
total -= numbers[i];
}
console.log(total);
#Output
-43
```

When working with collections of data in JavaScript, the ability to summarize the data easily is valuable.

One such case is if you want to subtract all numbers of an array.

To subtract all of the numbers of an array in JavaScript, the easiest way is with the **reduce()** method.

Below again we show you how to subtract all of the numbers of an array in JavaScript.

```
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function subtractArray(total, item) {
return total - item;
}
console.log(numbers.reduce(subtractArray));
#Output
-43
```

## Using a For Loop to Subtract All Numbers in an Array in JavaScript

Another way we can subtract all of the numbers of an array is with a for loop.

To subtract all of the numbers of an array, initialize a variable to the first number of the array, and then subtract each element from that number while keeping the running total.

Below shows you how to subtract all of the numbers of an array in JavaScript with a for loop.

```
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var total = numbers[0];
for( var i =1; i<numbers.length; i++ ){
total -= numbers[i];
}
console.log(total);
#Output
-43
```

We can put our code in a function so that we can reuse it as often as we like.

```
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function subtractArray(arr){
var total = numbers[0];
for( var i =1; i<numbers.length; i++ ){
total -= numbers[i];
}
return total;
};
console.log(subtractArray(numbers));
#Output
-43
```

Hopefully this article has been useful for you to learn how to subtract all numbers in an array in JavaScript.

## Leave a Reply