Skip to main content

Javascript Array Objects, Dense and Sparse Arrays

Array Data Structure, Javascript Array Object and Introduction to Dense and Sparse arrays.

In this story, I will cover the Array Data Structure and some interesting core facts about the Javascript Array Object that makes them different from the primitive array data structure in detail. To understand this story better, you should have a basic idea about arrays in javascript.

What is an array ?

“Array is a fixed size collection of homogeneous elements”. Array is one of the most simple data structures and probably, the most used data structure as well. Following are some of the features of array:

  • Fixed size Array has a predefined fixed size.
  • All the elements have same data type.
  • Every element is assigned an index starting from 0 to n-1, where n is number of elements.
  • Contiguous Memory Allocation Array is being allocated to continuous blocks of memory.
  • O(1) Time Complexity for Insert and Random Access.
  • O(n) Time Complexity for Delete and Search.

What is Array Object in Javascript ?

Arrays in Javascript are list-like global objects. Although, they work pretty much like a primitive array data structure but it is actually an API which is implemented using a Hash Table. Due to the use of Hash Table, arrays in javascript are more powerful as a structure.

  • Arrays in javascript are dynamic in size, whether you define the size initially or not.
let arr = new Array()
let arr = new Array(10);
let arr = [];
  • An Array in javascript can have elements with different data types.
let arr = [1,'hello',true,undefined]
  • Javascript supports both dense and sparse arrays.

What are dense and sparse arrays ?

Dense Arrays are only allocated contiguous blocks of memory.

Sparse Arrays doesn’t necessarily have to be allocated contiguous blocks of memory .

Why javascript supports sparse arrays ?

The answer is simple it allows arrays to be dynamic in size and data types. But most importantly, it improves memory utilization.

How to create a sparse array in javascript ?

Javascript tends to automatically create a sparse array if required in order to utilize the memory much efficiently. And javascript is doing this more often than you even notice. Consider the following example:

let arr = [1,2,3];
arr[50] = 50;

We have defined an array ‘arr’ with elements 1,2,3. Javascript allocates a contiguous memory for ‘arr’ after reading the first statement. Then javascript reads the second statement and allocates the memory for that element in memory. But here is the thing, it will not allocate memory for index 3 to index 49. Instead it will just allocate memory for index 50. See the block diagram below :

By this time there are two very important questions that needs to be answered.

What is the value in index 3 to 49 ?

console.log(arr[3],arr[4],arr[49])  
// output : undefined undefined undefined
console.log(arr.filter( a => a === undefined)
// output : []

If you try to check the value of any index from 3 to 49 of array ‘arr’, they all will be ‘undefined’. But, if you filter the array to only have ‘undefined’ values then the result will be an empty array. Because, in reality javascript never allocated memory to the index 3 to 49 as they were never declared.

What is the length of the array arr ?

Although the index 3 to 49 are empty and there are only 4 indexes with values. Still, the length of the array will be 51. Because, that’s how javascript manages the consistent indexes by making holes for non declared indexes.

console.log(arr.length)
// output : 51

Array Objects in javascript are amazing structures. But, if you want to create a primitive array data structure in javascript you can do that using typed arrays in javascript. Try that and let me know in response section if you find something cool.

Comments

Popular posts from this blog

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...