javascriptundefinedis-empty

Empty vs. Undefined in Javascript


In Javascript, if I make an array using Array(10), it creates an array with 10 empty items. If I access any item in that array, it returns undefined. However, if I create an array with a length of 10 and fill it with undefined like so: Array(10).fill(undefined), and access any item of that array, it also returns undefined. Similarly, if I were to coerce an empty value to a number using Number(), it returns 0. However, if I coerce undefined to a number by using Number(undefined), it returns NaN. How do I identify an empty value vs. a specifically undefined value?


Solution

  • Any "empty" items you are seeing are just your tools way of showing you have an array with fewer properties than your array length would indicate.

    var a = Array(3);
    console.log(Object.getOwnPropertyNames(a)); // ["length"]
    
    a.fill(undefined);
    console.log(Object.getOwnPropertyNames(a)); // ["0", "1", "2", "length"]

    There isn't really an empty value type in JavaScript, it's just the absence of a property, which you can detect in a variety of ways, with varying nuances in terms of walking the prototype chain and backwards compatibility with legacy software.

    var a = Array(3);
    console.log('0' in a); // false
    console.log(a.hasOwnProperty('0')); // false
    console.log(Reflect.has(a, '0')); // false
    
    
    a.fill(undefined);
    console.log('0' in a); // true
    console.log(a.hasOwnProperty('0')); // true
    console.log(Reflect.has(a, '0')); // true

    The reason you get undefined when you access one of these empty array slots is because that's the value you normally get when you access a property which does not exist on an object.


    Similarly, if I were to coerce an empty value to a number using Number(), it returns 0.

    This should not be happening according to the ES specification, all of these will produce NaN:

    a = Array(3);
    console.log(Number(a[0])); // NaN
    console.log(+a[0]); // NaN
    console.log(parseInt(a[0])); // NaN

    Passing no argument to Number() will produce 0 though.