0 votes
in JavaScript by
What are the different ways to create sparse arrays?

1 Answer

0 votes
by

There are 4 different ways to create sparse arrays in JavaScript

  1. Array literal: Omit a value when using the array literal
    const justiceLeague = ["Superman", "Aquaman", , "Batman"];
    console.log(justiceLeague); // ['Superman', 'Aquaman', empty ,'Batman']
  2. Array() constructor: Invoking Array(length) or new Array(length)
    const array = Array(3);
    console.log(array); // [empty, empty ,empty]
  3. Delete operator: Using delete array[index] operator on the array
    const justiceLeague = ["Superman", "Aquaman", "Batman"];
    delete justiceLeague[1];
    console.log(justiceLeague); // ['Superman', empty, ,'Batman']
  4. 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]

Related questions

0 votes
asked Oct 10, 2023 in JavaScript by DavidAnderson
0 votes
asked Oct 4, 2023 in JavaScript by DavidAnderson
...