How many types of JavaScript arrays

In JavaScript, there are several types of arrays based on their structure, contents, and usage.

Here are the main types of arrays:

1. Single-Dimensional Arrays
2. Multidimensional Arrays
3. Sparse Arrays
4. Typed Arrays
5. Array-Like Objects
6 Immutable Arrays (e.g., Immutable.js)
7. Custom Array Subclasses

Also read more topic in, Javascript Array.

1. Single-Dimensional Arrays:

  • Basic arrays with a linear collection of elements.
  • Accessed using numeric indices.
let numbers = [1, 2, 3, 4, 5];
console.log(numbers[2]); // Outputs: 3

2. Multidimensional Arrays:

  • Arrays containing other arrays as elements.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // Outputs: 6

3. Sparse Arrays:

A sparse array in JavaScript is an array where not all indices have corresponding values. In other words, there are “holes” or gaps in the sequence of indices. Sparse arrays are a result of not assigning a value to every index in the array. This is possible because JavaScript arrays are not required to have consecutive or continuous indices.

let sparseArray = [1, , 3, , 5];
console.log(sparseArray.length); // Outputs: 5

4. Typed Arrays:

Typed Arrays are a feature introduced in JavaScript as part of the ECMAScript 2015 (ES6) specification to work with low-level binary data directly. They provide a way to create and manipulate arrays of numeric data types, such as integers and floating-point numbers, in a more memory-efficient manner compared to regular JavaScript arrays.

Here are the key features and characteristics of Typed Arrays:
Data Types: Typed Arrays support a variety of data types, such as:

  • Int8, Uint8: 8-bit signed and unsigned integers
  • Int16, Uint16: 16-bit signed and unsigned integers
  • Int32, Uint32: 32-bit signed and unsigned integers
  • Float32: 32-bit floating-point numbers (single-precision)
  • Float64: 64-bit floating-point numbers (double-precision)

Memory Efficiency: Typed Arrays are memory-efficient because they store data in a more compact binary format. This is particularly useful when dealing with large amounts of data, like audio, image, or network data.
Fixed Size: Unlike regular JavaScript arrays that can dynamically grow or shrink, Typed Arrays have a fixed size upon creation. You can’t change their size without creating a new Typed Array.

Indexed Access: Similar to regular arrays, you can access Typed Array elements using indices.
Performance: Typed Arrays are optimized for performance, making them suitable for tasks involving data manipulation, computations, and interactions with binary data from sources like network protocols and file formats.
Buffer and View: Typed Arrays are often used in conjunction with ArrayBuffer objects, which represent a block of memory that can be shared between multiple Typed Arrays. Typed Arrays provide a view into the ArrayBuffer, allowing you to interpret and manipulate its data.

 // Create an ArrayBuffer
let buffer = new ArrayBuffer(8); // Allocate 8 bytes of memory

// Create a Typed Array view of the buffer
let intArray = new Int32Array(buffer);

// Set values
intArray[0] = 42;
intArray[1] = 88;

console.log(intArray); // Outputs: Int32Array [42, 88]
 

5. Array-Like Objects:

  • Objects resembling arrays.
let arrayLike = { 0: 'a', 1: 'b', length: 2 };
console.log(arrayLike[0]); // Outputs: 'a'

6. Immutable Arrays (e.g., Immutable.js):

Immutable arrays refer to arrays that cannot be modified after they are created. In JavaScript, arrays are mutable by default, meaning you can change their contents, add or remove elements, and modify their properties. However, there are libraries like Immutable.js that provide data structures, including arrays, which enforce immutability.

Using external libraries to create arrays that cannot be modified.

Here are the key characteristics and benefits of immutable arrays:
Immutable Data: Immutable arrays do not allow direct modification of their elements. Instead, any operation that would modify the array creates a new array with the desired changes, leaving the original array unchanged.
Preserve State: Because operations on immutable arrays create new arrays, previous versions are preserved. This can be useful for tracking changes over time or in undo/redo functionality.
Functional Programming: Immutable data aligns well with functional programming principles, making it easier to reason about code, parallelize operations, and avoid unintended side effects.
Predictable Updates: Since immutable arrays ensure that data remains constant, updates are predictable and don’t introduce unexpected changes elsewhere in the codebase.
Comparative Performance: While creating new arrays might seem inefficient, Immutable.js and similar libraries use structural sharing and advanced algorithms to optimize memory and performance.

const { List } = require('immutable');

const immutableList1 = List([1, 2, 3]);
const immutableList2 = immutableList1.push(4); // Creates a new list with 4 added

console.log(immutableList1.toArray()); // [1, 2, 3]
console.log(immutableList2.toArray()); // [1, 2, 3, 4]

7. Custom Array Subclasses:

Custom array subclasses in JavaScript allow you to create your own types of arrays with special features. You can make arrays that do more than just store values. For instance, you can add new methods to do specific tasks. This is like creating a new type of toy that’s based on a regular toy but does extra things.

class SpecialArray extends Array {
    // Custom method to find the average of all numbers
    average() {
        const total = this.reduce((sum, num) => sum + num, 0);
        return total / this.length;
    }
}

const numbers = new SpecialArray(1, 2, 3, 4, 5);

console.log(numbers); // Outputs: SpecialArray [1, 2, 3, 4, 5]
console.log(numbers.average()); // Outputs: 3
 

You can also discover a lot about Javascript by exploring different topics.

Note: We welcome your feedback at Easy coding School. Please don’t hesitate to share your suggestions or any issues you might have with the article!

3 thoughts on “How many types of JavaScript arrays

  1. I wanted to express my gratitude for taking the time to provide clarification on the 7.Custom Array Subclasses. Your explanation has been incredibly helpful, and I truly appreciate your dedication to helping me understand this important concept. Your support is invaluable to my learning journey.

    Thank you once again for your guidance.

Leave a Reply

Your email address will not be published. Required fields are marked *