JavaScript ยท Chapter 21 of 55

JavaScript Arrays

An array is an ordered list of values, useful for storing collections like a list of names or scores. Arrays are created with square brackets and are zero-indexed.

Arrays are a special kind of object in JavaScript, but come with many powerful built-in methods for adding, removing, and transforming elements.

Creating and accessing

`let fruits = ['apple', 'banana'];` creates an array. Access elements with `fruits[0]`, and get the count with `fruits.length`.

Adding and removing

`push()` adds to the end, `pop()` removes from the end, `unshift()` adds to the start, and `shift()` removes from the start.

Example 1 (javascript)
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[1]);
console.log(fruits.length);
Output
banana
3

Bracket indexing and .length work like strings.

Example 2 (javascript)
let nums = [1, 2, 3];
nums.push(4);
nums.pop();
console.log(nums);
Output
[1, 2, 3]

push adds 4, then pop removes the last element, net result unchanged.

Key points

  • Arrays are ordered, zero-indexed lists created with [].
  • `.length` returns the number of elements.
  • push/pop add/remove from the end; shift/unshift work on the start.
  • Arrays can hold mixed types, including other arrays and objects.
๐Ÿ’ก Note: Arrays are technically objects โ€” `typeof []` returns 'object', so use Array.isArray() to check.

๐Ÿ“ Quick Quiz

1. How do arrays start their index?

2. Which method adds an element to the end of an array?

3. Which removes an element from the beginning?