0

My goal is to check if there are empty values in an array of integers > 0:

given const array = [1, 4, , 7, 14] i expect a test to return false. You can get that result i.e. through !array.includes(undefined)

But if i use the function array.every(el => el !== undefined) it evaluates to true? So are empty elements in a js array undefined or a completely different data type?

Julian Dm
  • 89
  • 8
  • 1
    Duplicate of [How does JavaScript's forEach loop decide to skip or iterate through “undefined” and “null” elements in an Array?](https://stackoverflow.com/q/38658103/4642212). `array[2]` evaluates to `undefined`, because there is no such index. `Array` methods such as `forEach`, `map`, `every` _skip_ over these non-existent indexes. This has nothing to do with data types; there are no “empty elements” in the array, and asking what the data type would be is like asking what data type the `b` property in the object `({ a: 1, c: "hello" })` has — the question doesn’t make sense. – Sebastian Simon Mar 21 '21 at 13:14
  • 1
    maybe your are should look to somthing like this with empty string: const array = [1, 4, "", 7, 14] – Eric. M Mar 21 '21 at 13:18

2 Answers2

1

"Old style" array iterators (forEach and friends) don't iterate over indexes that don't physically exist in an array ("holes"):

a = [0, 1, , 3, 4]
a.forEach(x => console.log(x))

(Compare this to a "new style" iterator):

a = [0, 1, , 3, 4]
for (let x of a)
    console.log(x)

One way to detect holes is to run a counting old-style iterator over the array and compare the result to its length:

a = [0, 1, , 3, 4]
let count = a => a.reduce(c => c + 1, 0);
console.log(count(a) < a.length) // true -> has holes

If you're trying to detect any undefined value, both holes and "materialized" undefineds, use a "new style" spread to get a list of all values and apply some or every:

a = [0, 1, , 2, 4]
console.log([...a].some(x => x === undefined))


a = [0, 1, undefined, 2, 4]
console.log([...a].some(x => x === undefined))
georg
  • 195,833
  • 46
  • 263
  • 351
0

Using Object.getOwnPropertyNames() and Array.prototype.slice()

const array1 = [1, 4, , 7, 14],
  array2 = [1, 2, 3, 4],
  res = (array) =>
    Object.getOwnPropertyNames(array).slice(0, -1).length === array.length
      ? "No Empty"
      : "Yes Empty";
console.log(res(array1));
console.log(res(array2));