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

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

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 Denunciar

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 Denunciar

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 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