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

133
Vistas
Iterate over RegExp.exec(...)

From the RegExp.exec page on MDN, it gives the following example of iterating through a match with the g flag set:

const regex1 = RegExp('foo*', 'g');
const str1 = 'table football, foosball';
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
  // expected output: "Found foo. Next starts at 9."
  // expected output: "Found foo. Next starts at 19."
}

I have two questions about this code. The first one is why the !=== null is used here, why wouldn't the while loop be properly coded as:

while (array1 = regex1.exec(str1)) { // implicitly casts to boolean?
  console.log(`...`);

}

The above seems much more readable to me, but was wondering why the MDN docs used the first approach? Second, is it possible to declare and define the variable directly in the while loop? Something like:

while (let array1 = regex1.exec(str1)) { // don't need the `let array1` above?
  console.log(`...`);

}

Or is that not supported in the JS language?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Why the !== null is used here...?

True, in this case it is not needed. .exec() returns either an array or null, and since arrays are always truthy there is no need to explicitly compare with null.

Is it possible to declare and define the variable directly in the while loop?

No. If you want that, then turn to the for loop, which does support this:

for (let array1; array1 = regex1.exec(str1); null) {
  console.log(`...`);
}

This does indeed have the advantage that array1 has a more restricted scope. NB: I provided null to stress that the third part of the for header is intentionally unused.

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