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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...