JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Array Methods


JavaScript arrays are powerful not just because they store multiple values, but also because they come with a wide range of built-in methods that make manipulating, transforming, and querying arrays straightforward. Knowing array methods is essential for writing efficient and clean code, whether you are handling user input, processing data, or building complex applications. This tutorial covers the most commonly used array methods, practical examples, common mistakes, and best practices.

Why Array Methods Are Important

Array methods simplify tasks such as:

  • Adding or removing elements dynamically

  • Searching for specific items

  • Transforming arrays into new structures

  • Sorting and filtering data

  • Iterating over arrays efficiently

Without these methods, developers would have to write complex loops and manual operations, which can be error-prone and harder to maintain.

Commonly Used Array Methods

push()

Adds one or more elements to the end of an array and returns the new length.

let fruits = ["Apple", "Banana"];
fruits.push("Cherry");
console.log(fruits); // ["Apple", "Banana", "Cherry"]

pop()

Removes the last element of an array and returns it.

let lastFruit = fruits.pop();
console.log(lastFruit); // "Cherry"
console.log(fruits); // ["Apple", "Banana"]

unshift()

Adds one or more elements to the beginning of an array.

fruits.unshift("Mango");
console.log(fruits); // ["Mango", "Apple", "Banana"]

shift()

Removes the first element from an array and returns it.

let firstFruit = fruits.shift();
console.log(firstFruit); // "Mango"
console.log(fruits); // ["Apple", "Banana"]

concat()

Merges two or more arrays into a new array without modifying the originals.

let citrus = ["Orange", "Lemon"];
let allFruits = fruits.concat(citrus);
console.log(allFruits); // ["Apple", "Banana", "Orange", "Lemon"]

slice()

Returns a shallow copy of a portion of an array.

let someFruits = allFruits.slice(1, 3);
console.log(someFruits); // ["Banana", "Orange"]

splice()

Adds or removes elements at a specific index. This method modifies the original array.

allFruits.splice(2, 1, "Grapes"); 
console.log(allFruits); // ["Apple", "Banana", "Grapes", "Lemon"]

indexOf() and lastIndexOf()

indexOf() returns the first index of a value; lastIndexOf() returns the last occurrence.

let letters = ["A", "B", "C", "A"];
console.log(letters.indexOf("A")); // 0
console.log(letters.lastIndexOf("A")); // 3

includes()

Checks if an array contains a certain element.

console.log(letters.includes("B")); // true
console.log(letters.includes("D")); // false

join()

Combines array elements into a single string with a specified separator.

let colors = ["Red", "Green", "Blue"];
console.log(colors.join(", ")); // "Red, Green, Blue"

reverse()

Reverses the order of elements in an array.

colors.reverse();
console.log(colors); // ["Blue", "Green", "Red"]

sort()

Sorts elements. By default, it converts elements to strings and sorts lexicographically. For numbers, a compare function is needed.

let numbers = [40, 100, 1, 5];
numbers.sort(); // default string sort
console.log(numbers); // [1, 100, 40, 5]

numbers.sort((a, b) => a - b); // numeric ascending sort
console.log(numbers); // [1, 5, 40, 100]

map()

Creates a new array by applying a function to each element.

let nums = [1, 2, 3];
let squared = nums.map(n => n * n);
console.log(squared); // [1, 4, 9]

filter()

Creates a new array with elements that pass a test.

let scores = [65, 82, 45, 90];
let passing = scores.filter(score => score >= 50);
console.log(passing); // [65, 82, 90]

reduce()

Reduces an array to a single value by applying a function cumulatively.

let total = scores.reduce((sum, score) => sum + score, 0);
console.log(total); // 282

forEach()

Executes a function on each element but does not return a new array.

scores.forEach(score => console.log(score));

find() and findIndex()

find() returns the first element satisfying a condition; findIndex() returns its index.

let highScore = scores.find(score => score > 80);
console.log(highScore); // 82

let highScoreIndex = scores.findIndex(score => score > 80);
console.log(highScoreIndex); // 1

some() and every()

some() checks if at least one element passes a test; every() checks if all elements pass.

console.log(scores.some(score => score > 90)); // false
console.log(scores.every(score => score >= 45)); // true

Practical Examples

Example 1: Managing a Shopping List

let shopping = ["Milk", "Eggs", "Bread"];
shopping.push("Butter");
shopping.splice(1, 1); // Remove "Eggs"
console.log(shopping); // ["Milk", "Bread", "Butter"]

Example 2: Transforming Data

let numbers = [1, 2, 3, 4];
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]

Example 3: Filtering Students with High Scores

let studentScores = [45, 78, 90, 60];
let passed = studentScores.filter(score => score >= 60);
console.log(passed); // [78, 90, 60]

Example 4: Calculating Total Sales

let sales = [150, 200, 100, 250];
let totalSales = sales.reduce((sum, sale) => sum + sale, 0);
console.log(totalSales); // 700

Example 5: Searching for a Name

let names = ["Emma", "Lily", "Sophia"];
console.log(names.find(name => name.startsWith("S"))); // Sophia

Common Mistakes

  • Using sort() without a compare function for numbers.

  • Forgetting that splice() modifies the original array.

  • Expecting forEach() to return a new array; it does not.

  • Mixing up map(), filter(), and reduce() and using them incorrectly.

  • Confusing some() and every() in conditional checks.

Best Practices

  • Choose the correct method based on whether you need a new array or to modify the existing one.

  • Always consider performance for large arrays, especially with methods like reduce() and filter().

  • Use arrow functions for cleaner and more readable callbacks.

  • Keep transformations immutable when possible to avoid side effects.

  • Chain array methods carefully to maintain clarity.

Summary of JS Array Methods

JavaScript array methods provide an extensive toolkit to manipulate and process arrays efficiently. From adding and removing elements to searching, sorting, filtering, and transforming data, these methods reduce the need for manual loops and make your code more readable and maintainable. Understanding the nuances of each method, their return values, and side effects is essential for writing effective JavaScript code and handling data in real-world applications such as lists, forms, tables, and API responses. Mastering these methods allows developers to write cleaner, more robust, and scalable applications.


Practice Questions

Q1. How do you double all values in an array using a method?

Q2. Which method allows you to filter numbers greater than 50 in an array?

Q3. How do you find the sum of all numbers in an array?

Q4. Which method runs a function on each item but does not return a new array?

Q5. How do you remove the last element of an array?

Q6. What method is used to sort an array alphabetically?

Q7. How do you join elements of an array into a string separated by dashes (-)?

Q8. What method returns the index of a given value in an array?

Q9. How can you combine two arrays without modifying the original ones?

Q10. How do you reverse the order of elements in an array?


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top