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);
const colors = ["red", "green", "blue"]; creates an array containing three string values.const mixed = [42, "hello", true, null]; shows that an array can hold numbers, strings, booleans and null in the same list.console.log(colors); outputs the entire colors array.console.log(mixed); outputs the mixed-type array so you can see every element.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]);
const fruits = ["apple", "banana", "cherry"]; creates an array of three fruit names.console.log(fruits[0]); reads the element at index 0 and prints apple.console.log(fruits[1]); prints banana.console.log(fruits[5]); tries to read an index that does not exist. The result is undefined.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);
const cities = ["Tokyo", "Paris", "Cairo"]; starts with three cities.console.log(cities.length); prints 3.cities.push("Lima"); appends a new city to the end of the array.console.log(cities.length); now prints 4 because one element was added.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);
const stack = ["first", "second"]; creates a small array.stack.push("third"); appends the string "third". The array becomes ["first", "second", "third"].console.log(stack); prints the updated array.const removed = stack.pop(); removes the last element and stores it in removed.console.log(removed); prints third.console.log(stack); prints ["first", "second"].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);
const queue = ["B", "C"]; creates the initial array.queue.unshift("A"); inserts "A" at index 0. Everything else shifts one position to the right.console.log(queue); prints ["A", "B", "C"].const first = queue.shift(); removes the element at index 0 and stores it in first.console.log(first); prints A.console.log(queue); prints ["B", "C"].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));
const numbers = [10, 20, 30, 40];console.log(numbers.includes(30)); returns true because 30 is present.console.log(numbers.indexOf(30)); returns the index 2.console.log(numbers.indexOf(99)); returns -1 because 99 is not in the array.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);
const examScores = [88, 76, 95, 61, 84]; creates a five-element array of scores.const topThree = examScores.slice(0, 3); copies elements starting at index 0 up to (but not including) index 3. The result is [88, 76, 95].console.log(topThree); prints the new array.console.log(examScores); still shows the full original array.
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);
const examScores = [88, 76, 95, 61, 84]; creates the starting array.examScores.splice(1, 2, 99); starts at index 1, deletes 2 elements (76 and 95), then inserts 99 in their place.console.log(examScores); prints [88, 99, 61, 84].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);
const tags = ["travel", "photography", "nature"];console.log(tags.join(", ")); inserts a comma and space between each element, producing travel, photography, nature.const morningTasks = ["Feed cat", "Make coffee"];const eveningTasks = ["Water plants", "Lock doors"];const allTasks = morningTasks.concat(eveningTasks); creates a new array that contains every element from both source arrays. Neither original is modified.console.log(allTasks); prints the four-item result.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);
});
const attendees = ["Noah", "Aisha", "Liam"];attendees.forEach(function (name, index) { supplies a callback that receives each element as name and its position as index.console.log(index + 1 + ". " + name); builds a human-friendly numbered list (indexes start at 0, so we add 1).}); closes the callback and the forEach call.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));
const attendeeCounts = [8, 120, 25, 3];console.log([...attendeeCounts].sort()); copies the array first (so the original stays intact) then sorts it as strings. The result is [120, 25, 3, 8] because “120” comes before “25” alphabetically.console.log([...attendeeCounts].sort((a, b) => a - b)); uses a comparison function that subtracts the two numbers. A negative result means a should come first, producing the correct order [3, 8, 25, 120].
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]);
const seatingChart = [ begins a two-dimensional array.["Noah", "Aisha"], is the first inner array (row 0).["Liam", "Zara"] is the second inner array (row 1).];console.log(seatingChart[0][1]); prints Aisha.console.log(seatingChart[1][0]); prints Liam.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"]);
console.log(Array.isArray(["a", "b"])); returns true.console.log(Array.isArray({ a: 1 })); returns false.console.log(typeof ["a", "b"]); prints "object", which is why Array.isArray is needed.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);
const originalTags = ["urgent", "review"];const copiedTags = [...originalTags]; creates a new array containing the same elements.copiedTags.push("done"); adds an item to the copy only.console.log(originalTags); still shows ["urgent", "review"].console.log(copiedTags); shows ["urgent", "review", "done"].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);
const applicants = [{ name: "Noah", yearsExperience: 2 },{ name: "Aisha", yearsExperience: 6 },{ name: "Liam", yearsExperience: 4 }];const qualifiedNames = applicants.filter(applicant => applicant.yearsExperience >= 3) keeps only those with 3 or more years..map(applicant => applicant.name); turns the remaining objects into a simple array of name strings.console.log("Qualified applicants:", qualifiedNames); prints ["Aisha", "Liam"].Common Mistakes With Arrays
- Forgetting that array indexes start at
0, not1. - Using
sort()on numbers without a comparison function, resulting in incorrect string-based ordering. - Confusing
slice()(non-destructive) withsplice()(modifies the original array). - Assuming
typeofcan identify an array, whenArray.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 reservesplice()for when modifying the original array is intended. - Use
includes()for simple existence checks, andindexOf()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(), andshift()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);
const tasks = [{ title: "Write report", done: true },{ title: "Review budget", done: false },{ title: "Call client", done: false }];const remainingTasks = tasks.filter(task => !task.done); keeps only the objects whose done property is false.console.log(remainingTasks); prints the two unfinished tasks. Try adding, removing, or changing the filter condition.Tip: When you catch yourself writing a manualforloop to transform, filter, or total up an array, pause and check whethermap(),filter(), orreduce()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.
Click “Run Code” to see the output here.
Code Explanation
The complete example stays visible. Use Previous and Next to move through its logical blocks.
Select Next to begin exploring the code.