JS Coding Questions Logo
JS Coding Questions
#431💼 Interview💻 Code

What are the different ways to create sparse arrays?

Advertisement

728x90

There are 4 different ways to create sparse arrays in JavaScript

1. Array literal: Omit a value when using the array literal

js
1const justiceLeague = ["Superman", "Aquaman", , "Batman"];
2  console.log(justiceLeague); // ['Superman', 'Aquaman', empty ,'Batman']

2. Array() constructor: Invoking Array(length) or new Array(length)

js
1const array = Array(3);
2  console.log(array); // [empty, empty ,empty]

3. Delete operator: Using delete array[index] operator on the array

js
1const justiceLeague = ["Superman", "Aquaman", "Batman"];
2  delete justiceLeague[1];
3  console.log(justiceLeague); // ['Superman', empty, ,'Batman']

4. Increase length property: Increasing length property of an array

js
1const justiceLeague = ["Superman", "Aquaman", "Batman"];
2  justiceLeague.length = 5;
3  console.log(justiceLeague); // ['Superman', 'Aquaman', 'Batman', empty, empty]

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 2

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
431of476