JavaScript: Arrays
JavaScript Arrays
1 Overview
📘 Arrays
Arrays are special data structures used to store ordered collections of values. Unlike objects which store keyed collections, arrays maintain the order of elements and provide methods to manage that order. Arrays can hold values of any type and are zero-indexed (the first element is at index 0). They are essential for working with lists of data like users, products, or any sequential information.
2 Creating Arrays
There are two syntaxes for creating an empty array:
Recommendation: Use the square brackets []
syntax as it’s shorter and more common.
2.1 Array with Initial Elements
Array elements are numbered, starting with zero. We can get an element by its number in square brackets:
2.2 Modifying Elements
2.3 Adding New Elements
2.4 Array Length
The total count of elements in the array is its length
:
2.5 Displaying the Whole Array
2.6 Mixed Types
An array can store elements of any type:
3 Get Last Elements with “at”
To get the last element, we can use negative indices with the at()
method:
This is the same as:
4 Methods pop/push, shift/unshift
Arrays in JavaScript can work both as a queue and as a stack.
4.1 Queue (FIFO - First In First Out)
push
– appends an element to the endshift
– gets an element from the beginning
4.2 Stack (LIFO - Last In First Out)
push
– adds an element to the endpop
– takes an element from the end
4.3 pop
Extracts the last element of the array and returns it:
Both fruits.pop()
and fruits.at(-1)
return the last element, but fruits.pop()
also modifies the array by removing it.
4.4 push
Appends the element to the end of the array:
The call fruits.push(...)
is equal to fruits[fruits.length] = ...
.
4.5 shift
Extracts the first element of the array and returns it:
4.6 unshift
Adds the element to the beginning of the array:
4.7 Multiple Elements
Methods push
and unshift
can add multiple elements at once:
5 Performance
Methods push
/pop
are fast, while shift
/unshift
are slow.
Why?
push
/pop
work with the end of the array (no need to renumber other elements)shift
/unshift
work with the beginning (all elements need to be renumbered)
The more elements in the array, the more time to move them, more in-memory operations.
6 Loops
6.1 for Loop
The most common way to loop over array elements:
6.2 for…of Loop
A special form of loop for iterating over array values:
The for...of
doesn’t give access to the index, just the value. But that’s enough for most cases.
6.3 for…in Loop (Not Recommended)
Technically, because arrays are objects, it’s possible to use for...in
:
But this is a bad idea because: 1. for...in
iterates over all properties, not only numeric ones 2. for...in
is optimized for generic objects, not arrays (10-100 times slower)
Use for...of
or regular for
loop for arrays.
7 Array Length
The length
property automatically updates when we modify the array. It’s not the count of values, but the greatest numeric index plus one:
7.1 Clearing an Array
The simplest way to clear an array is:
8 new Array()
There’s one more syntax to create an array:
It’s rarely used because square brackets []
are shorter.
Gotcha: If new Array
is called with a single numeric argument, it creates an array without items, but with the given length:
9 Multidimensional Arrays
Arrays can have items that are also arrays. We can use it for multidimensional arrays:
10 toString
Arrays have their own implementation of toString
method that returns a comma-separated list of elements:
11 Don’t Compare Arrays with ==
Arrays in JavaScript shouldn’t be compared with operator ==
.
This operator has no special treatment for arrays, it works with them as with any objects.
Arrays are objects, so they are compared by reference. Two independent arrays are never equal.
11.1 Comparison with Primitives
When an array is compared with a primitive, it’s converted to a primitive for comparison.
Recommendation: Don’t use ==
with arrays. Instead, compare them item-by-item, or use iteration methods.
12 Common Array Methods
12.1 splice
The splice()
method can insert, remove and replace elements:
Examples:
12.2 slice
Returns a new array copying all items from index start
to end
(not including end
):
12.3 concat
Creates a new array that includes values from other arrays and additional items:
12.4 indexOf / lastIndexOf / includes
arr.indexOf(item, from)
– looks foritem
starting from indexfrom
, returns the index or-1
arr.lastIndexOf(item, from)
– same, but looks from right to leftarr.includes(item, from)
– looks foritem
starting from indexfrom
, returnstrue
if found
12.5 find and findIndex
Used to find objects with specific conditions:
12.6 filter
Returns an array of all matching elements:
12.7 map
Calls the function for each element and returns the array of results:
12.8 sort
Sorts the array in place, changing element order:
Note: Items are sorted as strings by default.
To sort numbers correctly:
12.9 reverse
Reverses the order of elements in the array:
12.10 split and join
str.split(delim)
splits the string into an array by the given delimiter:
arr.join(glue)
does the reverse – creates a string from array items glued by glue
:
12.11 reduce
Used to calculate a single value based on the array:
13 Examples
13.1 Example 1: Basic Array Operations
13.2 Example 2: Iterating Over Arrays
13.3 Example 3: Array Methods
let numbers = [1, 2, 3, 4, 5];
// map - double each number
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter - get even numbers
let evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// reduce - sum all numbers
let sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum); // 15
13.4 Example 4: Finding Elements
let users = [
{ id: 1, name: "John", age: 25 },
{ id: 2, name: "Jane", age: 30 },
{ id: 3, name: "Bob", age: 35 }
];
// find user with id 2
let user = users.find(u => u.id === 2);
console.log(user.name); // Jane
// filter users over 25
let adults = users.filter(u => u.age > 25);
console.log(adults.length); // 2
13.5 Example 5: Sorting
14 Summary
- Arrays are ordered collections of values
- Create arrays with
[]
ornew Array()
- Access elements by index:
arr[0]
,arr[1]
, etc. - Arrays are zero-indexed (first element is at index 0)
- Use
length
property to get the number of elements push
/pop
work with the end of the arrayshift
/unshift
work with the beginning of the array- Use
for...of
to iterate over array values - Use
map()
to transform array elements - Use
filter()
to select elements that match a condition - Use
find()
to find a single element - Use
reduce()
to calculate a single value from the array - Use
sort()
to sort array elements - Use
splice()
to insert, remove, or replace elements - Use
slice()
to copy a portion of an array - Use
concat()
to merge arrays - Don’t compare arrays with
==
operator