JavaScript Tutorial · Objects and Arrays · Lesson 23 of 44

JavaScript Arrays

Create arrays, access items and add, remove and find elements.

Creating arrays

An array is an ordered list of values. Indexes start at 0:

Example 1Try it yourself
const langs = ["JavaScript", "Python", "Go"];
console.log(langs[0]);
console.log(langs.at(-1));
console.log(langs.length);
langs[1] = "TypeScript";
console.log(langs);

Output

JavaScript
Go
3
[ 'JavaScript', 'TypeScript', 'Go' ]

Adding and removing

Method Does
push(x) / pop() add / remove at the end
unshift(x) / shift() add / remove at the start
splice(i, n, ...items) remove n items at i (and insert) — changes the array
slice(a, b) copy part of the array — doesn't change it
Example 2Try it yourself
const queue = ["a", "b"];
queue.push("c");
queue.unshift("z");
console.log(queue);
console.log(queue.pop(), queue.shift(), queue);
const letters = ["a", "b", "c", "d", "e"];
const removed = letters.splice(1, 2, "X");
console.log(removed, letters);
console.log(letters.slice(1, 3), letters);

Output

[ 'z', 'a', 'b', 'c' ]
c z [ 'a', 'b' ]
[ 'b', 'c' ] [ 'a', 'X', 'd', 'e' ]
[ 'X', 'd' ] [ 'a', 'X', 'd', 'e' ]

Searching

Example 3Try it yourself
const nums = [4, 8, 15, 16, 23, 42];
console.log(nums.includes(15));
console.log(nums.indexOf(16), nums.indexOf(99));
console.log(nums.find((n) => n > 10));
console.log(nums.findIndex((n) => n > 10));

Output

true
3 -1
15
2

Sorting

sort() changes the array and, without a compare function, sorts as strings — so always pass one for numbers. toSorted() returns a sorted copy instead:

Example 4Try it yourself
const n = [10, 1, 5, 100];
console.log([...n].sort());
console.log([...n].sort((a, b) => a - b));
console.log(n.toSorted((a, b) => b - a), n);
console.log(["pear", "Apple", "fig"].sort((a, b) => a.localeCompare(b)));

Output

[ 1, 10, 100, 5 ]
[ 1, 5, 10, 100 ]
[ 100, 10, 5, 1 ] [ 10, 1, 5, 100 ]
[ 'Apple', 'fig', 'pear' ]

Test yourself

What does [10, 1, 5].sort() return?

  1. [1, 5, 10]
  2. [10, 5, 1]
  3. [1, 10, 5]
  4. [5, 1, 10]
Show answer

Answer: [1, 10, 5]

Without a compare function, sort() compares items as strings: "1" < "10" < "5".

Practice next