Web Development /JavaScript Programming / Lesson
Web Development

JavaScript Arrays and Array Methods

Learn how JavaScript arrays store collections of values and how to use powerful array methods such as push(), pop(), map(), filter(), find(), reduce(), forEach(), sort() and more to process data efficiently.

🎯

Learning Objectives

["Understand what JavaScript arrays are and why they are useful.","Create arrays using array literals and the Array constructor.","Access array elements using indexes.","Add and remove elements from arrays.","Understand array length and how array indexes work.","Modify existing array elements.","Use forEach() to iterate through array values.","Use map() to create transformed arrays.","Use filter() to create arrays containing selected values.","Use find() and findIndex() to search arrays.","Use some() and every() to test array conditions.","Use includes() and indexOf() to check for values.","Use slice() and splice() for array extraction and modification.","Use concat() and spread syntax to combine arrays.","Use sort() and reverse() appropriately.","Use reduce() to calculate accumulated values.","Work with arrays containing objects.","Choose appropriate array methods when building real-world applications."]

📖

Lesson Content

Introduction to JavaScript Arrays

Arrays are one of the most important data structures in JavaScript. An array allows a program to store multiple values inside a single variable.

For example, instead of creating separate variables for several students:

const student1 = "Ade";
const student2 = "John";
const student3 = "Mary";

we can place the values inside one array:

const students = ["Ade", "John", "Mary"];

This makes it much easier to work with collections of information.

What Is an Array?

An array is an ordered collection of values. Each value is stored at a numbered position called an index.

const fruits = ["Apple", "Banana", "Orange"];

The indexes are:

  • 0 → Apple
  • 1 → Banana
  • 2 → Orange

JavaScript arrays use zero-based indexing, meaning the first element is at index 0.

Creating Arrays

The most common way to create an array is with square brackets.

const courses = [
    "Web Development",
    "Data Analysis",
    "Cyber Security"
];

An array can contain numbers:

const scores = [75, 82, 91, 68, 88];

It can also contain different types of values:

const profile = [
    "Ade",
    25,
    true
];

Although JavaScript allows mixed data types, applications are usually easier to maintain when arrays have a predictable structure.

Accessing Array Elements

Use the element’s index to access its value.

const fruits = ["Apple", "Banana", "Orange"];

console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

The result is:

Apple
Banana
Orange

Changing Array Elements

Array elements can be changed by assigning a new value to an existing index.

const fruits = ["Apple", "Banana", "Orange"];

fruits[1] = "Mango";

console.log(fruits);

The array now contains:

["Apple", "Mango", "Orange"]

The length Property

The length property tells us how many elements are currently in an array.

const students = ["Ade", "John", "Mary", "Grace"];

console.log(students.length);

The result is:

4

The last element can also be accessed using:

const lastStudent = students[students.length - 1];

console.log(lastStudent);

Adding Elements with push()

The push() method adds one or more elements to the end of an array.

const students = ["Ade", "John"];

students.push("Mary");

console.log(students);

Result:

["Ade", "John", "Mary"]

You can add multiple elements:

students.push("Grace", "David");

Removing Elements with pop()

The pop() method removes the last element from an array.

const students = ["Ade", "John", "Mary"];

const removedStudent = students.pop();

console.log(removedStudent);
console.log(students);

pop() returns the element that was removed.

Adding Elements with unshift()

The unshift() method adds one or more elements to the beginning of an array.

const students = ["John", "Mary"];

students.unshift("Ade");

console.log(students);

Result:

["Ade", "John", "Mary"]

Removing Elements with shift()

The shift() method removes the first element.

const students = ["Ade", "John", "Mary"];

const firstStudent = students.shift();

console.log(firstStudent);
console.log(students);

Iterating Through Arrays

When working with arrays, developers often need to process every element. JavaScript provides several useful iteration methods.

forEach()

The forEach() method executes a function once for every element in an array.

const students = ["Ade", "John", "Mary"];

students.forEach(function(student) {
    console.log(student);
});

Arrow functions can make the same code shorter:

students.forEach(student => {
    console.log(student);
});

forEach() is useful when you want to perform an action for each item without creating a new array.

map()

The map() method creates a new array by transforming every element.

const scores = [60, 70, 80];

const increasedScores = scores.map(score => score + 5);

console.log(increasedScores);

Result:

[65, 75, 85]

The original array remains unchanged:

console.log(scores);

filter()

The filter() method creates a new array containing only elements that satisfy a condition.

const scores = [45, 72, 88, 39, 91];

const passed = scores.filter(score => score >= 50);

console.log(passed);

Result:

[72, 88, 91]

This is especially useful when displaying selected records from a larger collection.

find()

The find() method returns the first element that satisfies a condition.

const scores = [45, 72, 88, 39, 91];

const result = scores.find(score => score > 80);

console.log(result);

The result is:

88

If no matching element is found, find() returns undefined.

findIndex()

findIndex() returns the index of the first matching element.

const scores = [45, 72, 88, 39, 91];

const index = scores.findIndex(score => score > 80);

console.log(index);

The result is:

2

includes()

The includes() method checks whether an array contains a specific value.

const courses = [
    "Web Development",
    "Data Analysis",
    "Cyber Security"
];

console.log(courses.includes("Data Analysis"));
console.log(courses.includes("Graphics Design"));

The results are:

true
false

indexOf()

The indexOf() method returns the position of a value.

const courses = [
    "Web Development",
    "Data Analysis",
    "Cyber Security"
];

console.log(courses.indexOf("Data Analysis"));

The result is:

1

If the value does not exist, indexOf() returns -1.

some()

The some() method checks whether at least one array element satisfies a condition.

const scores = [45, 49, 72, 38];

const hasPassed = scores.some(score => score >= 50);

console.log(hasPassed);

The result is true because at least one score is 50 or higher.

every()

The every() method checks whether all elements satisfy a condition.

const scores = [65, 72, 81, 90];

const allPassed = scores.every(score => score >= 50);

console.log(allPassed);

The result is true because every score is at least 50.

slice()

The slice() method creates a portion of an array without changing the original array.

const courses = [
    "HTML",
    "CSS",
    "JavaScript",
    "PHP",
    "MySQL"
];

const selectedCourses = courses.slice(1, 4);

console.log(selectedCourses);

Result:

["CSS", "JavaScript", "PHP"]

The ending index is not included.

splice()

The splice() method can add, remove or replace elements in an existing array.

const courses = [
    "HTML",
    "CSS",
    "JavaScript"
];

courses.splice(1, 1, "PHP");

console.log(courses);

Result:

["HTML", "PHP", "JavaScript"]

Unlike slice(), splice() modifies the original array.

concat()

The concat() method combines arrays into a new array.

const frontend = ["HTML", "CSS"];
const backend = ["PHP", "MySQL"];

const technologies = frontend.concat(backend);

console.log(technologies);

Result:

["HTML", "CSS", "PHP", "MySQL"]

Spread Syntax

The spread syntax provides another convenient way to combine arrays.

const frontend = ["HTML", "CSS"];
const backend = ["PHP", "MySQL"];

const technologies = [...frontend, ...backend];

console.log(technologies);

Spread syntax is also useful when creating a new array based on an existing array.

const original = ["HTML", "CSS"];

const copy = [...original];

console.log(copy);

reverse()

The reverse() method reverses the order of elements in an array.

const numbers = [1, 2, 3, 4];

numbers.reverse();

console.log(numbers);

Result:

[4, 3, 2, 1]

reverse() modifies the original array.

sort()

The sort() method sorts array elements.

const names = ["John", "Ade", "Mary", "Grace"];

names.sort();

console.log(names);

For numbers, a comparison function should normally be supplied because JavaScript’s default sorting treats values as strings.

const scores = [100, 25, 8, 75, 42];

scores.sort((a, b) => a - b);

console.log(scores);

For descending order:

scores.sort((a, b) => b - a);

reduce()

The reduce() method processes an array and produces a single accumulated result.

For example, we can calculate the total of several scores:

const scores = [70, 80, 90, 60];

const total = scores.reduce(
    (sum, score) => sum + score,
    0
);

console.log(total);

The result is:

300

reduce() is useful for totals, averages, calculations, grouping and other data-processing operations.

Calculating an Average

We can combine reduce() with length to calculate an average.

const scores = [70, 80, 90, 60];

const total = scores.reduce(
    (sum, score) => sum + score,
    0
);

const average = total / scores.length;

console.log(average);

Arrays of Objects

Real applications often store objects inside arrays.

const students = [
    {
        name: "Ade",
        score: 85
    },
    {
        name: "John",
        score: 72
    },
    {
        name: "Mary",
        score: 91
    }
];

We can access individual properties:

console.log(students[0].name);
console.log(students[1].score);

We can also use array methods with objects.

Filtering Objects

const students = [
    { name: "Ade", score: 85 },
    { name: "John", score: 42 },
    { name: "Mary", score: 91 }
];

const passedStudents = students.filter(
    student => student.score >= 50
);

console.log(passedStudents);

Mapping Objects

We can use map() to extract or transform information.

const students = [
    { name: "Ade", score: 85 },
    { name: "John", score: 42 },
    { name: "Mary", score: 91 }
];

const names = students.map(student => student.name);

console.log(names);

The result is:

["Ade", "John", "Mary"]

Chaining Array Methods

Array methods can be combined to perform multiple operations.

const students = [
    { name: "Ade", score: 85 },
    { name: "John", score: 42 },
    { name: "Mary", score: 91 },
    { name: "Grace", score: 48 }
];

const passedNames = students
    .filter(student => student.score >= 50)
    .map(student => student.name);

console.log(passedNames);

The first method selects the students who passed. The second method extracts their names.

Practical Example: Student Result Processor

Consider a training platform that stores student scores.

const scores = [72, 45, 88, 91, 39, 67];

const passed = scores.filter(score => score >= 50);

const total = scores.reduce(
    (sum, score) => sum + score,
    0
);

const average = total / scores.length;

const highest = Math.max(...scores);

const lowest = Math.min(...scores);

console.log("Passed:", passed);
console.log("Total:", total);
console.log("Average:", average);
console.log("Highest:", highest);
console.log("Lowest:", lowest);

This demonstrates how arrays and their methods can be used to process real student data.

Mutating vs Non-Mutating Methods

Some array methods change the original array, while others create a new array.

Methods such as push(), pop(), shift(), unshift(), splice(), sort() and reverse() modify the original array.

Methods such as map(), filter(), slice() and concat() return new arrays without directly modifying the original array.

Understanding this difference is important when building larger applications because unexpected changes to shared data can create difficult bugs.

Choosing the Right Array Method

  • Use forEach() when you need to perform an action for each element.
  • Use map() when you need a transformed array.
  • Use filter() when you need only elements that meet a condition.
  • Use find() when you need the first matching element.
  • Use findIndex() when you need the position of the first matching element.
  • Use some() when at least one item must satisfy a condition.
  • Use every() when all items must satisfy a condition.
  • Use reduce() when multiple values need to become one result.
  • Use includes() when checking whether a specific value exists.
  • Use slice() when extracting part of an array without modifying it.
  • Use splice() when intentionally adding, removing or replacing elements in the original array.

Common Beginner Mistakes

1. Forgetting Zero-Based Indexing

const names = ["Ade", "John", "Mary"];

console.log(names[0]);

The first element is at index 0, not index 1.

2. Accessing an Invalid Index

console.log(names[10]);

If the index does not exist, JavaScript returns undefined.

3. Forgetting that sort() Handles Numbers Differently

For numerical sorting, use a comparison function:

numbers.sort((a, b) => a - b);

4. Accidentally Modifying an Array

Remember that methods such as splice(), sort() and reverse() modify the original array.

Best Practices

  • Use const when the array variable itself does not need to be reassigned.
  • Choose descriptive array names such as students, courses or scores.
  • Use the array method that clearly communicates your intention.
  • Prefer map(), filter() and other suitable methods when they make data processing clearer.
  • Be careful when using mutating methods.
  • When sorting numbers, always use an appropriate comparison function.
  • When working with arrays of objects, keep object structures consistent.
  • Break complicated array operations into readable steps when necessary.

Practice Exercise

Create an array containing the names and scores of at least six students.

Your program should:

  1. Display all students.
  2. Display only students who scored at least 50.
  3. Create a new array containing only the student names.
  4. Calculate the total score.
  5. Calculate the average score.
  6. Find the highest score.
  7. Find the lowest score.
  8. Check whether at least one student scored 90 or above.
  9. Check whether every student scored at least 40.

Lesson Summary

Arrays allow JavaScript applications to store and process collections of values. They are fundamental to web applications because information such as users, products, courses, posts, transactions and scores is often represented as collections.

You have learned how to create arrays, access and modify elements, add and remove items, iterate through arrays and process data using methods such as map(), filter(), find(), reduce(), some() and every().

Mastering arrays is an important step toward working with dynamic web applications, APIs, databases and JavaScript frameworks.

💻

Code Example

const students = [
    { name: "Ade", score: 85 },
    { name: "John", score: 42 },
    { name: "Mary", score: 91 },
    { name: "Grace", score: 68 },
    { name: "David", score: 47 }
];

// Students who passed
const passedStudents = students.filter(
    student => student.score >= 50
);

// Extract student names
const studentNames = students.map(
    student => student.name
);

// Calculate total score
const totalScore = students.reduce(
    (total, student) => total + student.score,
    0
);

// Calculate average
const averageScore = totalScore / students.length;

// Highest score
const highestScore = Math.max(
    ...students.map(student => student.score)
);

// Lowest score
const lowestScore = Math.min(
    ...students.map(student => student.score)
);

// Check conditions
const hasExcellentStudent = students.some(
    student => student.score >= 90
);

const allAboveForty = students.every(
    student => student.score >= 40
);

console.log("Passed Students:", passedStudents);
console.log("Student Names:", studentNames);
console.log("Total Score:", totalScore);
console.log("Average Score:", averageScore);
console.log("Highest Score:", highestScore);
console.log("Lowest Score:", lowestScore);
console.log("Has Student With 90+:", hasExcellentStudent);
console.log("All Students Above 40:", allAboveForty);
⭐

Key Takeaways

["JavaScript arrays store ordered collections of values.","Array indexes start from zero.","The length property returns the number of elements.","push() and unshift() add elements.","pop() and shift() remove elements.","forEach() performs an operation for each element.","map() transforms array elements into a new array.","filter() creates a new array containing matching elements.","find() returns the first matching element.","findIndex() returns the index of the first matching element.","some() checks whether at least one element satisfies a condition.","every() checks whether all elements satisfy a condition.","includes() checks whether a value exists in an array.","slice() extracts part of an array without modifying the original.","splice() can add, remove or replace elements in the original array.","reduce() can turn multiple values into one accumulated result.","Arrays of objects are commonly used to represent application data.","Understanding mutation is important when working with arrays.","Choosing the correct array method makes JavaScript code clearer and easier to maintain."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress