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

121
Visualizações
Can someone help me interpret the if statement in this javascript code?
function filterArray(array, callback) {
  const newArray = [];
  for (let i = 0; i < array.length; i += 1) {
    if (callback(array[i])) newArray.push(array[i]);
  }
  return newArray;
}

I'm confused by the syntax. Typically what I've seen so far is

if (condition) {
  // code to be executed
}

where condition is some boolean statement which will run the code shown if condition = true.

But, in this if statement, there is no boolean, nor is there code to be executed after the conditonal statement. I have no clue what it means. Thanks in advance for any help interpeting it.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

(callback(array[i])) this part is the condition. newArray.push(array[i]) this is what happens when the condition is met. It just looks so close together.

if (callback(array[i])) 
{
   newArray.push(array[i])
}

Does same thing.

about 4 years ago · Juan Pablo Isaza Relatório

0

There is a boolean, namely the value returned from calling the function callback with argument array[i]. (To be precise: The interpretation of the returned value as a truth value according to the JavaScript language specs - this is what is meant by 'truthy' or 'falsy'. For starters just assume that callback does indeed return a boolean value)

There also is code being executed: The first statement after the condition. This is just a notational shorthand. The verbose equivalent code would be:

if (callback(array[i])) {
    newArray.push(array[i]);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

if (callback(array[i])) newArray.push(array[i]); simply means that callback is a function, that gets called and a return value is expected (could be any value, not only boolean). Then, if the return is truthy, the statement newArray.push(array[i]); gets executed.

(A single line if (exp) statement; can be written like this, but may sometimes hide bugs, so some linters prefer to always change it to

if (exp) {
  statement;
}

Callbacks are typically functions that get passed in as an argument (exactly as you see here) that then may get called.

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