Skip to content

Arrays

Arrays in JavaScript are quite different from arrays in languages like C++. Unlike C++'s fixed-size arrays, JavaScript arrays can grow and shrink dynamically and hold any type of value, similar to Python's lists. They behave more like dynamic lists or array lists in other languages.

Creating Arrays

There are several ways to create arrays:

js
// Empty array
const empty = [];

// Array with initial values
const numbers = [1, 2, 3, 4, 5];
// Mix any types (like Python lists)
const mixed = [1, "hello", true, { key: "value" }];

// Using the Array constructor
const sized = new Array(3);     // Creates array of length 3, but elements are undefined

Accessing Elements

Array elements are accessed using zero-based indexing:

js
const fruits = ["apple", "banana", "orange"];
console.log(fruits[0]);     // "apple"
console.log(fruits[1]);     // "banana"

The length property tells us how many elements are in the array:

js
const fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // 3

Reading an index beyond the array's bounds returns undefined:

js
const fruits = ["apple", "banana"];
console.log(fruits[2]);     // undefined

Elements can be modified using the same index method.

js
const fruits = ["apple", "banana", "orange"];

// Modify existing elements
fruits[1] = "grape";        // This works
console.log(fruits);        // ["apple", "grape", "orange"]

Unlike C++, JavaScript arrays automatically grow when you assign to an index beyond their current length:

js
const fruits = ["apple", "banana", "orange"];
fruits[3] = "mango";        // Automatically extends the array
console.log(fruits.length); // 4
console.log(fruits[5]);     // undefined (no error for reading past end)

Like all objects in JavaScript, array variables are references to the array in memory. When using const, only this reference is immutable, meaning you can't make the variable point to a different array. The array's contents can still be modified through this reference:

js
// But we can't reassign the array itself
// fruits = ["pear", "plum"];  // Error: Assignment to constant variable

Iteration

JavaScript provides several ways to iterate over arrays:

js
const items = ["a", "b", "c"];

// Traditional for loop
for (let i = 0; i < items.length; i++) {
    console.log(items[i]);
}

// for...of loop (better)
for (const item of items) {
    console.log(item);
}

// forEach method (often best)
items.forEach(item => console.log(item));

💡 Arrays in JavaScript are actually objects with special behaviours for numeric indices and a length property. This explains their flexibility with types and sizing, but also means they can be slower than typed arrays in languages like C++.

External Resources