Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

276
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda