InterviewHubPRO
Section Overview
Q435

Question 435 of 521

Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

83%
JavaScript Internals (521 Qs)•Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

What are the different ways to create sparse arrays?

There are 4 different ways to create sparse arrays in JavaScript

  1. Array literal: Omit a value when using the array literal
js
    const justiceLeague = ["Superman", "Aquaman", , "Batman"];
    console.log(justiceLeague); // ['Superman', 'Aquaman', empty ,'Batman']
  1. Array() constructor: Invoking Array(length) or new Array(length)
js
    const array = Array(3);
    console.log(array); // [empty, empty ,empty]
  1. Delete operator: Using delete array[index] operator on the array
js
    const justiceLeague = ["Superman", "Aquaman", "Batman"];
    delete justiceLeague[1];
    console.log(justiceLeague); // ['Superman', empty, ,'Batman']
  1. Increase length property: Increasing length property of an array
js
    const justiceLeague = ["Superman", "Aquaman", "Batman"];
    justiceLeague.length = 5;
    console.log(justiceLeague); // ['Superman', 'Aquaman', 'Batman', empty, empty]