Search code examples
javascriptvariablestypesundefined

Difference between not initialized and undefined value


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.


Solution

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