Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
What is return -1 in javascript?

What is the return -1 on the third to last line of the below code? How does it work and what is its use?

function findElement(arr) {
    let right_sum = 0, left_sum = 0;
    
    for (let i = 1; i < arr.length; i++) {
        right_sum += arr[i];
        
        for (let i = 0, j = 1; j < arr.length; i++, j++) {
            right_sum -= arr[j];
            left_sum += arr[i];
            
            if (left_sum === right_sum) {
                return arr[i + 1];
            }
        }
        
        return -1; // what is this?
    }
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The return operator is used to return a value from inside a function, so the code return -1; makes the findElement function return the value -1 (negative 1) if the for loop doesn't work. This is useful for debugging. If the for loop works, then the function will return arr[i + 1].

about 4 years ago · Juan Pablo Isaza Report

0

It looks like the developer of that piece of code decided to return -1 if the for loop failed to return a value for error checking.

Its common for people to do these kinds of returns as it helps with error handling.

about 4 years ago · Juan Pablo Isaza Report

0

It seems to be simulation of native arrays indexOf method. It returns -1 too, if no matches found.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!