Sub topic 1
Arrays in JavaScript: Creation, Indexing, and length
An array is an ordered list of values stored under one variable. In JavaScript, arrays are special objects. Their keys are numeric positions, and they keep a length property that tracks those positions automatically. This chapter covers creating arrays, reading and writing elements by index, and how length behaves.
Prerequisites
This chapter assumes you already know:
- How to declare variables with
letandconst - How to write functions and arrow functions
- How objects and property access (
obj.key,obj['key']) work - Basic control flow, such as
ifandforloops - How to run JavaScript in a browser console or Node.js
Creating Arrays
The array literal, a comma-separated list inside square brackets, is the usual way to create an array:
const empty = [];
const fruits = ['apple', 'banana', 'cherry'];
const mixed = [42, 'text', true, null, { id: 1 }, [1, 2]];
console.log(Array.isArray(fruits)); // true
console.log(typeof fruits); // 'object'Arrays can hold values of any type, mixed together, including other arrays. Because typeof reports 'object' for an array, use Array.isArray() when you need to check whether a value is an array.
Indexing
Elements are numbered from zero. The first element is at index 0 and the last is at length - 1.
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // 'apple'
console.log(fruits[fruits.length - 1]); // 'cherry'
console.log(fruits[5]); // undefined (no error)
fruits[1] = 'blueberry';
console.log(fruits); // ['apple', 'blueberry', 'cherry']Reading an index that doesn't exist returns undefined and does not throw an error. Bugs caused by this can go unnoticed for a long time. Writing to an existing index replaces the value at that position.
How length Behaves
length is always one greater than the highest index, and you can write to it:
const nums = [1, 2, 3, 4, 5];
console.log(nums.length); // 5
nums.length = 2;
console.log(nums); // [1, 2] (truncated)
nums[4] = 9;
console.log(nums.length); // 5
console.log(nums); // [1, 2, <2 empty items>, 9]Setting length to a smaller number deletes every element past that point, and those values are lost. Assigning to an index past the end makes the array longer and leaves empty slots, called holes, in between. An array with holes is a sparse array, and a later chapter covers its edge cases.
Common Errors
| Mistake | Result | Fix |
|---|---|---|
| `arr[arr.length]` to get the last item | `undefined` | Use `arr[arr.length - 1]` or `arr.at(-1)` |
| `arr[-1]` to get the last item | `undefined` | Use `arr.at(-1)` (next chapter) |
| `typeof arr === 'array'` | Always `false` | Use `Array.isArray(arr)` |
| Writing far past the end | Sparse array with holes | Add elements with `push` instead |
Exercise
Given const a = ['x', 'y', 'z'];, what do a[3] and a.length show after you run a[5] = 'w';?
Show answer
a[3] is undefined because index 3 is an empty slot. a.length is 6, one more than the highest index, 5.
Exercise
How do you remove every element from const list = [1, 2, 3]; without reassigning list?
Show answer
Set list.length = 0;. This truncates the array in place, which is allowed for a const binding.