CodeMIRAI
0 XP

Arrays

2 min read 8 runnable examples Quiz included

An array is an ordered list of values in square brackets.

JavaScript
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);           // first item: index 0
console.log(fruits.length);
console.log(fruits[fruits.length - 1]);
console.log(fruits.at(-1));       // last item, the modern way

Changing items

JavaScript
const scores = [70, 85, 90];
scores[1] = 88;
console.log(scores);

Adding and removing

MethodDoesReturns
push(x)adds to the endnew length
pop()removes from the endremoved item
unshift(x)adds to the startnew length
shift()removes from the startremoved item
JavaScript
const queue = ["Asha", "Leo"];
queue.push("Mei");
queue.unshift("Raj");
console.log(queue);

const last = queue.pop();
const first = queue.shift();
console.log(first, last, queue);

splice: remove or insert anywhere

JavaScript
const letters = ["a", "b", "c", "d", "e"];
const removed = letters.splice(1, 2);     // from index 1, remove 2 items
console.log(removed, letters);
letters.splice(1, 0, "X", "Y");           // insert without removing
console.log(letters);

slice: copy part of an array

slice doesn't change the original:

JavaScript
const nums = [10, 20, 30, 40, 50];
console.log(nums.slice(1, 3));
console.log(nums.slice(-2));
console.log(nums);

Searching

JavaScript
const pets = ["cat", "dog", "fish", "dog"];
console.log(pets.includes("fish"));
console.log(pets.indexOf("dog"));
console.log(pets.indexOf("lion"));        // -1 means not found
console.log(pets.lastIndexOf("dog"));

Looping with for...of

JavaScript
const cities = ["Mumbai", "London", "Osaka"];
for (const city of cities) {
  console.log(city);
}

Joining and sorting

JavaScript
const words = ["banana", "apple", "cherry"];
console.log(words.join(", "));
console.log([...words].sort());              // copy, then sort

const numbers = [10, 9, 100, 1];
console.log([...numbers].sort());            // text order: 1, 10, 100, 9
console.log([...numbers].sort((a, b) => a - b));
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.