Home > Mobile >  Is `if (idx < arr.length)` equivalent to `if (arr[idx])`?
Is `if (idx < arr.length)` equivalent to `if (arr[idx])`?

Time:12-22

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])?

CodePudding user response:

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.

CodePudding user response:

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]);
  • Related