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

143
Vistas
Is `if (idx < arr.length)` equivalent to `if (arr[idx])`?

Assuming that all elements inside an array have a value different from undefined, null or 0, is

if (idx < arr.length) equivalent to if (arr[idx])?

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

0

No.

There are other falsy values that will evaluate to false in the if statement, such as an empty string (''):

const arrWithEmptyString = ['', '', ''];
const idx = 2;

console.log(!!(idx < arrWithEmptyString.length));
console.log(!!arrWithEmptyString[idx]);

Alternatively, what if the array contains a boolean false?

const boolArray = [true, false, true, false]
const idx = 3;
console.log(!!(idx < boolArray.length));
console.log(!!boolArray[idx]);

Type coercion/type conversion in JS can be confusing and unpredictable-- in my opinion it is generally better to be explicit and test exactly what it is you mean to test, rather than relying on weak type comparisons to save a few characters.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Nice answer from Alexander Nied, also NaN evaluates to false

const boolArray = [NaN, NaN, NaN, NaN]
const idx = 3;
console.log(!!(idx < boolArray.length));
console.log(!!boolArray[idx]);
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