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

What is the difference between dense and sparse arrays?

Advertisement

728x90

An array contains items at each index starting from first(0) to last(array.length - 1) is called as Dense array. Whereas if at least one item is missing at any index, the array is called as sparse.

Let's see the below two kind of arrays,

js
1const avengers = ["Ironman", "Hulk", "CaptainAmerica"];
2
3console.log(avengers[0]); // 'Ironman'
4
5console.log(avengers[1]); // 'Hulk'
6
7console.log(avengers[2]); // 'CaptainAmerica'
8
9console.log(avengers.length); // 3
10
11const justiceLeague = ["Superman", "Aquaman", , "Batman"];
12
13console.log(justiceLeague[0]); // 'Superman'
14
15console.log(justiceLeague[1]); // 'Aquaman'
16
17console.log(justiceLeague[2]); // undefined
18
19console.log(justiceLeague[3]); // 'Batman'
20
21console.log(justiceLeague.length); // 4

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 1

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
430of476
What is the difference between dense and sparse arrays? | JSCodingQuestions.com