sum of negative integers in javascript

Here's an example code of how to sum the negative integers in a given array using JavaScript:

index.tsx
const arr = [1, -2, 3, -4, 5, -6];
let sum = 0;

for (let i = 0; i < arr.length; i++) {
  if (arr[i] < 0) {
    sum += arr[i];
  }
}

console.log(sum);
152 chars
11 lines

This code will output the sum of all the negative integers in the array arr. Here, we have initialized the sum variable to 0 and used a for loop to iterate over each element of the array. We have checked every element against zero and add them to the sum variable if they are negative using the if statement. At last, we console.log the sum.

related categories

gistlibby LogSnag