Academic Block

JavaScript Arrays Get Certified

Arrays are ordered lists of values. They are one of the most frequently used data structures in JavaScript and form the foundation for many everyday programming tasks.

In this lesson, you will learn how to create arrays, add and remove elements, extract portions, sort, iterate, and work with nested arrays.

Creating Arrays

The most common way to create an array is with square brackets (array literal syntax).

What this code does: An array literal creates an ordered list of values. You can mix different types, though keeping a single type is usually clearer.

const colors = ["red", "green", "blue"];
const mixed = [42, "hello", true, null];
console.log(colors);
console.log(mixed);

Accessing Elements

Array indexes start at 0. Use square brackets to read the value at a specific position.

What this code does: Indexes begin at 0. Reading an index that does not exist returns undefined.

const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[5]);

Array Length

The length property tells you how many elements an array currently contains. It updates automatically when you add or remove items.

What this code does: length reports the current number of elements. After push the length increases by one.

const cities = ["Tokyo", "Paris", "Cairo"];
console.log(cities.length);
cities.push("Lima");
console.log(cities.length);

push() and pop()

push() adds one or more items to the end of an array. pop() removes and returns the last item.

What this code does: push grows the array from the end; pop shrinks it and returns the removed value.

const stack = ["first", "second"];
stack.push("third");
console.log(stack);
const removed = stack.pop();
console.log(removed);
console.log(stack);

unshift() and shift()

unshift() adds items at the beginning of an array. shift() removes and returns the first item.

What this code does: unshift inserts at the front; shift removes from the front. Both change the indexes of every remaining element.

const queue = ["B", "C"];
queue.unshift("A");
console.log(queue);
const first = queue.shift();
console.log(first);
console.log(queue);

Finding Elements

includes() returns true or false depending on whether a value exists. indexOf() returns the first index of a value, or -1 if it is missing.

What this code does: includes answers the yes/no question “is this value present?”. indexOf gives the position (or -1 when the value is absent).

const numbers = [10, 20, 30, 40];
console.log(numbers.includes(30));
console.log(numbers.indexOf(30));
console.log(numbers.indexOf(99));

slice() and splice()

slice(start, end) returns a new array containing elements from start up to (but not including) end. The original array is left untouched.

What this code does: slice copies a portion into a brand-new array. The original stays the same.

const examScores = [88, 76, 95, 61, 84];
const topThree = examScores.slice(0, 3);
console.log(topThree);
console.log(examScores);

splice(start, deleteCount, ...items) can remove, insert, or replace elements. It modifies the original array and returns the removed elements.

What this code does: splice both removes and inserts at a chosen position, changing the original array.

const examScores = [88, 76, 95, 61, 84];
examScores.splice(1, 2, 99);
console.log(examScores);

join() and concat()

join() turns an array into a single string, inserting a separator between elements. concat() merges two or more arrays into a new array without changing the originals.

What this code does: join builds a readable string; concat combines two arrays into one new array.

const tags = ["travel", "photography", "nature"];
console.log(tags.join(", "));
const morningTasks = ["Feed cat", "Make coffee"];
const eveningTasks = ["Water plants", "Lock doors"];
const allTasks = morningTasks.concat(eveningTasks);
console.log(allTasks);

Iterating Over an Array

forEach runs a callback once for every element. The callback receives the element, its index, and the whole array.

What this code does: forEach visits every element. The index and name are used to print a numbered list of attendees.

const attendees = ["Noah", "Aisha", "Liam"];
attendees.forEach(function (name, index) {
    console.log(index + 1 + ". " + name);
});

Sorting Arrays

sort() sorts an array in place. Without a comparison function, it sorts elements as strings by default, which can lead to surprising results with numbers.

What this code does: Default sort converts values to strings and can order numbers wrong. Passing (a, b) => a - b sorts numbers correctly from smallest to largest.

const attendeeCounts = [8, 120, 25, 3];
console.log([...attendeeCounts].sort());
console.log([...attendeeCounts].sort((a, b) => a - b));

Notice how the default sort treats 120 as coming before 25, since it compares them as text. Passing a comparison function like (a, b) => a - b sorts numbers correctly.

Arrays of Arrays

An array can contain other arrays, which is useful for representing grids or tables of data.

What this code does: Arrays can contain other arrays (nested arrays). Access inner values with chained indexes: row first, then column.

const seatingChart = [
    ["Noah", "Aisha"],
    ["Liam", "Zara"]
];
console.log(seatingChart[0][1]);
console.log(seatingChart[1][0]);

Checking for Arrays

Because typeof returns "object" for arrays, use Array.isArray() to reliably check whether a value is actually an array.

What this code does: typeof reports arrays as "object". Use Array.isArray() to reliably check whether a value is an array.

console.log(Array.isArray(["a", "b"]));
console.log(Array.isArray({ a: 1 }));
console.log(typeof ["a", "b"]);

Copying Arrays

Just like objects, assigning an array to a new variable copies the reference, not the data. Use the spread operator to create an independent copy.

What this code does: The spread operator creates an independent shallow copy. Pushing onto the copy does not change the original array.

const originalTags = ["urgent", "review"];
const copiedTags = [...originalTags];
copiedTags.push("done");
console.log(originalTags);
console.log(copiedTags);

Key Array Methods Overview

Method Effect Modifies Original?
push() / pop() Add / remove from the end Yes
unshift() / shift() Add / remove from the beginning Yes
slice() Extract a portion into a new array No
splice() Remove/insert elements at a position Yes
map() / filter() Transform / select elements into a new array No
sort() Sort elements Yes

Practical Example

Let’s combine several array methods together to process a list of job applicants.

What this code does: Chain filter and map to select applicants with enough experience and then extract only their names.

const applicants = [
    { name: "Noah", yearsExperience: 2 },
    { name: "Aisha", yearsExperience: 6 },
    { name: "Liam", yearsExperience: 4 }
];
const qualifiedNames = applicants
    .filter(applicant => applicant.yearsExperience >= 3)
    .map(applicant => applicant.name);
console.log("Qualified applicants:", qualifiedNames);

Common Mistakes With Arrays

  • Forgetting that array indexes start at 0, not 1.
  • Using sort() on numbers without a comparison function, resulting in incorrect string-based ordering.
  • Confusing slice() (non-destructive) with splice() (modifies the original array).
  • Assuming typeof can identify an array, when Array.isArray() should be used instead.
  • Copying an array with = and expecting an independent copy, instead of a shared reference.

Best Practices for Arrays

  • Always pass a comparison function to sort() when working with numbers.
  • Use slice() or the spread operator when you need a copy, and reserve splice() for when modifying the original array is intended.
  • Use includes() for simple existence checks, and indexOf() when you need the actual position.
  • Keep arrays focused on a single type of data whenever possible, for predictability and easier debugging.

Quick Summary

  • Arrays store ordered lists of values, accessed by a zero-based index.
  • push(), pop(), unshift(), and shift() add or remove elements at the beginning or end.
  • slice() copies a portion without modifying the original; splice() modifies the array directly.
  • Array.isArray() reliably checks whether a value is an array.
  • Use the spread operator to create an independent copy of an array.

Try It Yourself

Modify the array below. Try adding a new task, removing one, or using filter() to show only tasks that aren’t marked complete.

What this code does: Practice example: filter unfinished tasks, add or remove items, then click Test My Code to see the result.

const tasks = [
    { title: "Write report", done: true },
    { title: "Review budget", done: false },
    { title: "Call client", done: false }
];
const remainingTasks = tasks.filter(task => !task.done);
console.log(remainingTasks);
Tip: When you catch yourself writing a manual for loop to transform, filter, or total up an array, pause and check whether map(), filter(), or reduce() would express the same idea more clearly.

Understanding arrays is essential before moving on to array destructuring, higher-order functions, and more advanced JavaScript concepts.

🧪 Test Your JavaScript Code

Edit the code on the left and click “Run Code” to see the console output on the right.

📝 JavaScript Code
👁 Console Output

Click “Run Code” to see the output here.

Ctrl + Enter to run code Esc to close