DEV Community

Discussion on: 6 Different Ways to Insert Elements to an Array in JavaScript

Collapse
 
peerreynders profile image
peerreynders • Edited

5a. Using index position

const a = ['1', '2', '3'];
const i = 5;
a[i] = '4';

console.log(a); // (6) [ "1", "2", "3", empty x 2, "4" ]
                // Array(6) [ "1", "2", "3", <2 empty slots>, "4" ]
a[i - 1] = undefined;
console.log(a); // (6) [ "1", "2", "3", empty, undefined, "4" ]
                // Array(6) [ "1", "2", "3", <1 empty slot>, undefined, "4" ]

console.log(a.hasOwnProperty(i - 2)); // empty → false 
console.log(a.hasOwnProperty(i - 1)); // undefined → true 
Enter fullscreen mode Exit fullscreen mode

empty is a pseudo value used to represent a hole in an array.

ECMAScript 6: holes in Arrays
Elements kinds in V8