3
let a = Array(3);
a[0] = 1;
a[1] = undefined;

function test(arr) {
  return arr.map(a => !!a);
}

console.log('before', a); // [1, undefined, undefined]
console.log('after', test(a)); // [true, false, undefined]

How can I check if array element is initialized as undefined (a[1]) or not initialized (a[2])? a[2] has empty value, but browser converts it to undefined.

  • Does this answer your question? [JavaScript "new Array(n)" and "Array.prototype.map" weirdness](https://stackoverflow.com/questions/5501581/javascript-new-arrayn-and-array-prototype-map-weirdness) – derpirscher Jun 20 '22 at 14:51
  • @derpirscher: That does not explain how to determine whether a value has been set or not, at any index. – Cerbrus Jun 20 '22 at 14:52
  • Well, your "bug" turned out to be one way to test :D. Not going to say if this is the best method or not, though, so keep looking for answers! – Rashad Saleh Jun 20 '22 at 14:56
  • what is actually the wanted result? `map` returns `undefined` for sparse items. – Nina Scholz Jun 20 '22 at 15:14

1 Answers1

3

You can use hasOwnProperty with the index.
When no value at the index is set, hasOwnProperty returns false:

const a = Array(3);
a[1] = undefined;

console.log(a.hasOwnProperty(0));
console.log(a.hasOwnProperty(1));
console.log(a.hasOwnProperty(2));

in works as well:

const a = Array(3);
a[1] = undefined;

console.log(0 in a);
console.log(1 in a);
console.log(2 in a);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147