JS Arrays with Examples: A Beginner-Friendly Guide

JS Arrays with Examples: A Beginner-Friendly Guide

An array is an ordered list. Think of a shopping list, a playlist or the results of a search: many values stored under one name. JS arrays are one of the first data structures you meet, and you will use them in almost every project you build.

This guide covers creating arrays, reading and changing them, and the handful of methods that do most of the work. Everything below was written to run as-is in Node or your browser console. If variables are still fuzzy, start with JavaScript variables and data types.

Creating an array

Use square brackets and separate items with commas. An array can hold any mix of values, though it is usually cleaner to keep one type per array.

const fruits = ["apple", "banana", "mango"];
const empty = [];

console.log(fruits);        // [ 'apple', 'banana', 'mango' ]
console.log(fruits.length); // 3

Using const here does not freeze the contents. It only means the variable cannot point to a different array. You can still add and remove items.

Reading items by index

Each item has a position called an index, and counting starts at zero, not one. This surprises almost everyone at first.

const fruits = ["apple", "banana", "mango"];

console.log(fruits[0]);                  // apple
console.log(fruits[2]);                  // mango
console.log(fruits[fruits.length - 1]);  // mango (the last item)
console.log(fruits.at(-1));              // mango (shorter way)
console.log(fruits[10]);                 // undefined, no such item

Asking for an index that does not exist gives undefined rather than an error, which can hide bugs if you are not watching for it.

Adding and removing items

Four methods cover the basics:

  • push adds to the end.
  • pop removes from the end.
  • unshift adds to the start.
  • shift removes from the start.
const queue = ["a", "b"];
queue.push("c");     // [ 'a', 'b', 'c' ]
queue.unshift("z");  // [ 'z', 'a', 'b', 'c' ]
const last = queue.pop();   // removes 'c'
const first = queue.shift(); // removes 'z'

console.log(queue, first, last); // [ 'a', 'b' ] z c

These methods change the original array. Developers call that mutating it, and it matters later when several parts of a program share the same array.

Looping through an array

The cleanest loop for reading every item is for...of:

const scores = [70, 85, 92];
for (const score of scores) {
  console.log("Score:", score);
}
// Score: 70
// Score: 85
// Score: 92

There are several other styles, and we compare them in the JS loops guide.

Related reading: JavaScript Functions Explained for Beginners: Complete Guide

The big three: map, filter and reduce

These methods take a function and apply it to the items. They return a new value and leave the original array alone, which makes them safer than loops that change things in place.

map: transform every item

const prices = [100, 200, 300];
const withTax = prices.map((p) => Math.round(p * 1.18));
console.log(withTax); // [ 118, 236, 354 ]

filter: keep only some items

const ages = [12, 18, 25, 9, 40];
const adults = ages.filter((age) => age >= 18);
console.log(adults); // [ 18, 25, 40 ]

reduce: boil the list down to one value

const cart = [250, 100, 50];
const total = cart.reduce((sum, price) => sum + price, 0);
console.log(total); // 400

The 0 at the end is the starting value of sum. Always provide it, or an empty array will throw an error.

Removing from the middle

When the item you want to remove is not at either end, use splice(start, count). It removes items in place and returns what it removed. Be careful, because the name looks a lot like slice, and the two behave very differently: slice leaves the original alone, splice does not.

const days = ["Mon", "Tue", "Wed", "Thu"];
const removed = days.splice(1, 2); // from index 1, remove 2 items
console.log(removed); // [ 'Tue', 'Wed' ]
console.log(days);    // [ 'Mon', 'Thu' ]

Searching

  • includes(value) tells you true or false.
  • indexOf(value) gives the position, or -1 if it is missing.
  • find(fn) returns the first item that passes your test.
const users = [{ name: "Asha", id: 1 }, { name: "Ravi", id: 2 }];
console.log(users.find((u) => u.id === 2)); // { name: 'Ravi', id: 2 }
console.log([1, 2, 3].includes(2));          // true

That example also shows an array of objects, a very common shape for real data. See JS objects with real examples to learn how those items work.

Copying and slicing

Assigning one array to another variable does not copy it. Both names point to the same list.

const a = [1, 2, 3];
const b = a;            // same array, not a copy
b.push(4);
console.log(a);         // [ 1, 2, 3, 4 ]

const c = [...a];       // a real (shallow) copy using spread
c.push(5);
console.log(a, c);      // [ 1, 2, 3, 4 ] [ 1, 2, 3, 4, 5 ]

Use slice(start, end) to take a piece without changing the original. The spread syntax is one of the handy additions covered in JavaScript ES6 features.

Sorting gotcha

By default, sort() compares items as text, so numbers come out in a strange order. Pass a comparison function:

const nums = [10, 9, 1, 100];
console.log([...nums].sort());              // [ 1, 10, 100, 9 ]
console.log([...nums].sort((x, y) => x - y)); // [ 1, 9, 10, 100 ]

Pulling values out with destructuring

When you know what the first few items are, destructuring lets you name them in one line instead of indexing each one.

const [first, second] = ["gold", "silver", "bronze"];
console.log(first, second); // gold silver

Common mistakes

  • Expecting the first item to be at index 1.
  • Thinking const makes the array unchangeable.
  • Forgetting to copy before sorting, which reorders the original.
  • Using map when you only want a loop with side effects.

More lessons like this live in the JavaScript category.

Conclusion

Arrays are simple at heart, and a few methods get you far:

  • Indexes start at 0, and length is the item count.
  • push, pop, shift and unshift change the array in place.
  • map, filter and reduce create new results from existing data.
  • Copy with spread before you change a shared array.
  • Give sort a comparison function for numbers.

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Your comment will appear after moderation.