JavaScript/Arrays
[i]Learn· JavaScript language overview

Arrays

Arrays in JavaScript are actually a special type of object. They work very much like regular objects (numerical properties can naturally be accessed only using [] syntax) but they have one magic property called length. This is always one more than the highest index in the array.

Arrays are usually created with array literals:

const a = ["dog", "cat", "hen"];
a.length; // 3

JavaScript arrays are still objects — you can assign any properties to them, including arbitrary number indices. The only "magic" is that length will be automatically updated when you set a particular index.

const a = ["dog", "cat", "hen"];
a[100] = "fox";
console.log(a.length); // 101
console.log(a); // ['dog', 'cat', 'hen', empty × 97, 'fox']

The array we got above is called a sparse array because there are uninhabited slots in the middle, and will cause the engine to deoptimize it from an array to a hash table. Make sure your array is densely populated!

Out-of-bounds indexing doesn't throw. If you query a non-existent array index, you'll get a value of undefined in return:

const a = ["dog", "cat", "hen"];
console.log(typeof a[90]); // undefined

Arrays can have any elements and can grow or shrink arbitrarily.

const arr = [1, "foo", true];
arr.push({});
// arr = [1, "foo", true, {}]

Arrays can be iterated with the for loop, as you can in other C-like languages:

for (let i = 0; i < a.length; i++) {
  // Do something with a[i]
}

Or, since arrays are iterable, you can use the for...of loop, which is synonymous to C++/Java's for (int x : arr) syntax:

for (const currentValue of a) {
  // Do something with currentValue
}

Arrays come with a plethora of array methods. Many of them would iterate the array — for example, map() would apply a callback to every array element, and return a new array:

const babies = ["dog", "cat", "hen"].map((name) => `baby ${name}`);
// babies = ['baby dog', 'baby cat', 'baby hen']
Source: JavaScript language overview by Mozilla Contributors, licensed under CC-BY-SA-2.5. Retrieved 2026-11-18. Changes: Extracted the section "Arrays"; removed the code-block language labels; made links absolute; examples are the page's own code blocks, unchanged.