Adding numbers continuously until a negative number is reached

I need help understanding how to utilize the index 0 within a for-loop while evaluating an empty array for cumulative sum. Additionally, I am looking to return zero when encountering a single negative value, and the summation process should halt upon encountering any negative number.

  
let sum = 0;

let lenArr = arr.length;

for (let i = 0; i <= lenArr - 1; i++) {
  if (lenArr === 0) {
    break;
  }

  if (arr[i] > 0) {
    sum = sum + arr[i];
  } else {
    break;
  }
}

return sum;
}

let input = [];

runningSum(input);

Answer №1

If the array is empty, the for loop will not run and the function will return 0. Consider removing the if statement that checks the length of the array inside the for loop.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Keypress Event not Functioning with Image Control in Asp.Net

Struggling to capture key press events on an image control in asp.net. The code I've tried doesn't seem to be working. Here's what I have: <head runat="server"> <title></title> <script type="text/javascript" language="j ...

"Resetting select fields in a Django application using jQuery: A step-by-step guide

Recently, I was tasked with taking over a partially-developed Django application. Python is familiar territory for me, but I am completely new to JavaScript. This application heavily relies on jQuery for various form manipulations. One specific issue I enc ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...

An Ajax call nested within another Ajax call

I've implemented an AJAX request to load my "home" page and "about" page into a designated "container" when a menu link button is clicked on my index.php. Now, I have three links on my "home" page and I want each of these links to open within the same ...

Is it possible to create a function that executes if a checkbox is checked, and another function if

When the radio button with the ID m1 is checked, my mesh updates its position. I attempted to make the mesh return to its original position if "#m1" is no longer checked. Is it necessary to trigger a function when checked and a different function when no ...

What is causing the high value of scannedObjects in MongoDB even though all query fields are indexed?

My query is running slow while indexing three fields on a large collection, one of which is an array. Despite using the correct index, the number of scanned objects is high, resulting in poor performance with 300K fields. The exaggerated number of scanned ...

Working with a two-dimensional array in Java: printing values using a for loop

I'm attempting to create a two-dimensional for loop that will display the following pattern: 7 5 3 1 2 4 6 8 Below is my array: int [][] secondArray = {{7, 5, 3, 1}, {2, 4, 6, 8}}; The current for loop provided only prints one number ...

Uncovering hidden links in a menu with Python Selenium and JavaScript

Can someone provide guidance on how to activate the JavaScript submenu associated with this button, "x-auto-54"? <table id="x-auto-54" class=" x-btn avtar-x-btn x-component x-btn-noicon x-unselectable " cellspacing="0" role="prese ...

Is there a way to have incoming messages automatically align to the left or right based on the sender, without using the float property?

I am currently working on a webpage where I want the messages sent by different users to appear in a yellow conversation window based on who sent them - user 1 or user 2. I want it to mimic the messaging layout commonly seen on phones, distinguishing betwe ...

What causes HttpPostedFileBase to fail on large files before reaching server-side validation?

When I disable client side validation <add key="ClientValidationEnabled" value="false" /> <add key="UnobtrusiveJavaScriptEnabled" value="false" /> and attempt to upload a file that is approximately 11 MB, which is then assigned to a HttpPost ...

Retrieving information from a JSON reply within an Angular 2 service

I am currently utilizing a service in angular 2 that retrieves JSON data from an API (). The code for fetching the data is depicted below: getImages() { return this.http.get(`${this.Url}`) .toPromise() .then(response => response.json() ...

Moving between different perspectives within a single-page backbone application

I am interested in incorporating dynamic transitions similar to the ones showcased on this website into a single-page backbone application. However, I am unsure of where to begin. Do I need to modify how I initialize my views (currently using a standard sw ...

What is the best method to determine the currency associated with the code in dinero.js?

Is there an easy way to locate the dinero currency in the dinero.js/currencies package using its code? For example, a function called getCurrency that accepts a string as input and outputs the corresponding dinero currency. ...

Slider with FadeIn effect remains unresponsive to the FadeOut command (JQuery / Javascript)

I'm currently working on a slider that is supposed to fade in and out. However, I am facing an issue where the slide fades in correctly but instantly disappears instead of fading out. Do you have any insights into why this might be happening and any s ...

The issue persists as the ng-change directive fails to function despite the presence of ng-model in AngularJS

Greetings everyone. Despite searching online for a solution to my issue, I have been unable to resolve it. Below is the HTML5 code snippet I am working with: <!DOCTYPE html> <html> <head> </head> <body ng-app="myApp ...

Validate the quantity of JSON data

My JSON result looks something like this: array ( 'status' => 'sukses', 'msg' => 'Resi Ada', 'gen_info' => array ( 'awb' => '030003437484', 'service&ap ...

Navigate through the page and once you reach a specific point, scroll the element

I'm feeling a bit stuck on how to achieve this particular effect. Imagine a web page where, as a user scrolls down, a specific element responds to the mouse scroll input by appearing to move along with the scrolling motion. Once that element reaches ...

Tips for extracting a portion of a string in JavaScript:

I'm dealing with a string that looks like this: var str1="tag:youtube.com,2008:video:VrtMalb-XcQ"; I want to extract the last part of the string, which is VrtMalb-XcQ. What's the best way to do this? ...

Maximum of 100 objects retrieved in ajax request using JavaScript

I am trying to increase the size of the response that is returned by this ajax call from the default 100 to a larger value. Here's what my ajax call looks like: var request2 = $.ajax({ type: "GET", url: "https://appscan87:9443/ase/api ...

The error message "ReferenceError: process is not defined" is caused by a module located at "../../node_modules/graphql/jsutils/instanceOf

While working on my latest project, an Instagram clone, I made use of GraphQL subscriptions to implement the functionality for liking/unliking posts. For my client, I utilized npx create-react-app to set up the front end and express for the server. Within ...