JavaScript question detail
What are the different ways to create sparse arrays?
There are 4 different ways to create sparse arrays in JavaScript
- Array literal: Omit a value when using the array literal
const justiceLeague = ["Superman", "Aquaman", , "Batman"];
console.log(justiceLeague); // ['Superman', 'Aquaman', empty ,'Batman']
- Array() constructor: Invoking Array(length) or new Array(length)
const array = Array(3);
console.log(array); // [empty, empty ,empty]
- Delete operator: Using delete array[index] operator on the array
const justiceLeague = ["Superman", "Aquaman", "Batman"];
delete justiceLeague[1];
console.log(justiceLeague); // ['Superman', empty, ,'Batman']
- Increase length property: Increasing length property of an array
const justiceLeague = ["Superman", "Aquaman", "Batman"];
justiceLeague.length = 5;
console.log(justiceLeague); // ['Superman', 'Aquaman', 'Batman', empty, empty]