Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

280
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda