Sub topic 1
Arrays in JavaScript: Creation, Indexing, and length
An array is an ordered list of values stored under one name. JavaScript arrays hold values of any type, resize themselves as you add or remove items, and come with a large set of built-in methods. Later chapters cover those methods. This chapter covers the foundation they rely on: how arrays are created, how positions are numbered, and how the length property actually behaves.
Prerequisites
This chapter assumes you are comfortable with:
- Declaring variables with
letandconst - Writing functions and arrow functions
- Objects and property access with dot and bracket notation
- Basic control flow such as
ifstatements andforloops - Running JavaScript in a browser console or with Node.js
Every example below runs as-is in Node.js or a browser console.
Creating Arrays
Array literals
The usual way to create an array is an array literal: a comma-separated list inside square brackets.
const fruits = ['apple', 'banana', 'cherry'];
const empty = [];
const mixed = [42, 'text', true, null, { id: 1 }, [1, 2]];
console.log(fruits.length); // 3
console.log(empty.length); // 0
console.log(mixed.length); // 6An array can mix types freely, as mixed shows, and it can contain other arrays. In practice, arrays where every element has the same shape (all numbers, or all user objects) are much easier to process with methods like map and filter.
The Array constructor and its trap
You can also call Array() or new Array(). Its behavior depends on the arguments, and that makes it easy to get wrong:
console.log(new Array(1, 2, 3)); // [1, 2, 3]
console.log(new Array('3')); // ['3']
console.log(new Array(3).length); // 3, but no elements were storedWith a single numeric argument, the constructor creates an array with that length and no elements in it. You get empty slots, not three undefined values. Prefer literals. When you need to build an array from a count or another source, use Array.of and Array.from, which a later chapter covers.
Arrays are objects
Arrays are a special kind of object. Their indices are property keys, and length is a property that the engine keeps in sync with those keys.
const list = [10, 20];
console.log(typeof list); // 'object'
console.log(Array.isArray(list)); // true
console.log(Array.isArray({ 0: 10, length: 1 })); // falseBecause typeof cannot tell an array from a plain object, use Array.isArray() whenever you need to check.
Indexing
Zero-based positions
Each element sits at an index, a whole number counted from 0. The first element is at index 0, and the last is at length - 1.
Read an element with bracket notation:
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // 'apple'
console.log(fruits[2]); // 'cherry'
console.log(fruits[fruits.length - 1]); // 'cherry'
console.log(fruits[3]); // undefined
console.log(fruits[10]); // undefinedReading past the end does not throw an error. It quietly returns undefined, the same result you get for any missing object property. This is a common cause of off-by-one bugs: a loop condition written as i <= arr.length runs one extra time and processes an undefined that nobody intended.
Negative indices are not "from the end"
In Python, list[-1] gives the last element. In JavaScript, arr[-1] looks up a property literally named "-1", and arrays don't have one:
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[-1]); // undefined
fruits[-1] = 'oops';
console.log(fruits[-1]); // 'oops'
console.log(fruits.length); // 3, because "-1" is an ordinary property, not an elementOnly non-negative integers count as array indices. To read from the end, use fruits[fruits.length - 1] or the at() method from the next chapter.
Index keys are strings underneath
Property keys are strings, so fruits[1] and fruits['1'] refer to the same element. A non-integer key such as fruits[1.5] or fruits['first'] creates a regular property, which methods and length ignore. Stick to integer indices.
Updating by index
Assigning to an index replaces the element at that position:
const fruits = ['apple', 'banana', 'cherry'];
fruits[1] = 'blueberry';
console.log(fruits); // ['apple', 'blueberry', 'cherry']Note that fruits is declared with const. The const keyword prevents reassigning the variable (fruits = [] throws a TypeError), but it does not stop you from changing the array's contents. To prevent element changes, use Object.freeze(fruits). After freezing, assignments are silently ignored in sloppy mode and throw in strict mode.
Nested arrays
An array of arrays gives you a simple grid. Chain the brackets to reach inner elements:
const grid = [
[1, 2, 3],
[4, 5, 6]
];
console.log(grid[1][2]); // 6
console.log(grid.length); // 2 (rows)
console.log(grid[0].length); // 3 (columns in row 0)If an outer index is out of range, grid[5] is undefined, and grid[5][0] then throws a TypeError. Optional chaining, written grid[5]?.[0], returns undefined instead of throwing.
How length Really Works
length is one more than the highest index
length does not count the elements actually stored. It equals the highest integer index plus one. Usually the two numbers match. When you assign far past the end, they don't:
const letters = ['a', 'b'];
letters[5] = 'f';
console.log(letters.length); // 6
console.log(letters[3]); // undefined
console.log(3 in letters); // false, so index 3 is a hole, not a stored undefinedIndices 2 through 4 are now holes, which makes letters a sparse array. Methods treat holes inconsistently. The edge-cases chapter covers this, so for now the advice is simple: don't create holes on purpose.
Writing to length
length is writable. Setting it lower deletes every element at or above the new length. Setting it higher adds empty slots.
const nums = [1, 2, 3, 4, 5];
nums.length = 2;
console.log(nums); // [1, 2]
nums.length = 4;
console.log(nums.length); // 4
console.log(nums[3]); // undefined (a hole)
nums.length = 0;
console.log(nums); // []Setting arr.length = 0 is a known idiom for emptying an array in place. Every variable that refers to that array sees the change. By contrast, arr = [] binds a single variable to a brand-new array and leaves the old one untouched for anyone else holding a reference. The difference between changing an array in place and creating a new one comes up again in the chapter on mutating methods.
Appending with length
Because length points one slot past the last element, arr[arr.length] = value appends an element. It works, but push() states the intent more clearly. The chapter on adding and removing elements covers it.
const queue = ['job1'];
queue[queue.length] = 'job2';
console.log(queue); // ['job1', 'job2']Common Errors at a Glance
| Mistake | What happens | Fix |
|---|---|---|
| `arr[arr.length]` to read the last item | Returns `undefined` | Use `arr[arr.length - 1]` or `arr.at(-1)` |
| `arr[-1]` expecting the last item | Reads or creates a property named `"-1"` | Use `arr.at(-1)` |
| `i <= arr.length` in a loop | One extra iteration over `undefined` | Use `i < arr.length` |
| `new Array(5)` expecting `[5]` | Five empty slots | Use `[5]` or `Array.of(5)` |
| `typeof arr === 'array'` | Always false, because `typeof` gives `'object'` | Use `Array.isArray(arr)` |
| Assuming `const` freezes contents | Elements can still change | Use `Object.freeze` if needed |
Exercise
What does this code log, and why? const a = ['x', 'y', 'z']; a.length = 1; a[3] = 'w'; console.log(a.length, a[1], 1 in a);
Show answer
It logs 4 undefined false. Setting length to 1 deletes 'y' and 'z'. Assigning to index 3 makes length 3 + 1 = 4. Index 1 is now a hole, so a[1] reads as undefined and the in operator reports that no element exists there.
Exercise
Write a function last(arr) that returns the final element of an array, or undefined for an empty array, without using at().
Show answer
const last = arr => arr[arr.length - 1]; For an empty array, arr.length - 1 is -1, and arr[-1] is undefined because no property named "-1" exists. The function therefore needs no special case, as long as nobody has assigned to a "-1" property.
Exercise
Two variables refer to the same array: let a = [1, 2, 3]; let b = a; What are a and b after running a = [] instead of a.length = 0?
Show answer
After a = [], a is a new empty array and b is still [1, 2, 3], because only the variable a was rebound. With a.length = 0, the shared array is emptied in place, so both a and b would be [].