| Property | empty slot | undefined |
|---|---|---|
| How it is created | Created by sparse array syntax such as new Array(5) | Explicit assignment like arr[0] = undefined |
| Whether a value exists | No value is stored at all | A value exists, and that value is undefined |
| Access result | arr[i] // undefined because the slot does not exist | arr[i] // undefined |
in operator | i in arr // false | i in arr // true |
hasOwnProperty | arr.hasOwnProperty(i) // false | arr.hasOwnProperty(i) // true |
JSON.stringify | Empty slots may be skipped | The position is preserved as a value |
map / forEach iteration | That index is skipped | That index is iterated normally |
| Example difference | [ , , 3] -> length = 3, but the first two positions are empty slots | [undefined, undefined, 3] -> length = 3, and the first two positions do contain values |
const arr1 = new Array(3); // [ <3 empty items> ]const arr2 = [undefined, undefined, undefined];
console.log(0 in arr1); // false -> the slot does not existconsole.log(0 in arr2); // true -> the value exists and is undefined
console.log(arr1.hasOwnProperty(0)); // falseconsole.log(arr2.hasOwnProperty(0)); // true
arr1.forEach((x, i) => console.log(i, x)); // prints nothingarr2.forEach((x, i) => console.log(i, x)); // prints 0 undefined, 1 undefined, 2 undefinedQuick memory trick: