← Back to Chapters

JavaScript Arrays

? JavaScript Arrays

⚡ Quick Overview

In JavaScript, an array is a special variable that can hold multiple values at once. Arrays are zero-indexed (the first item is at index 0) and can store values of different types (strings, numbers, objects, etc.) in a single list-like structure.

Arrays are one of the most important data structures in JavaScript and are heavily used for handling collections of data, loops, transformations, and more.

? Key Concepts

  • Arrays are created using square brackets [].
  • Each element in an array has an index starting from 0.
  • length gives the number of elements in the array.
  • Arrays can store mixed data types (strings, numbers, booleans, objects).
  • const prevents reassigning the array variable, but you can still change its contents.
  • JavaScript provides many built-in methods for adding, removing, searching, sorting, and iterating.

? Syntax and Basics

An array is usually created with a comma-separated list of values inside square brackets. You can access elements by their index and check how many items an array has using the length property.

? View Basic Array Example
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]);    // "Apple"
console.log(fruits[1]);    // "Banana"
console.log(fruits.length); // 3

? Using const with Arrays

Declaring an array with const means you cannot reassign the variable to a new array, but you can still modify the elements inside the array (add, remove, update).

? View const Array Example
const colors = ["Red", "Green"];
colors.push("Blue");     // Allowed: ["Red", "Green", "Blue"]
colors[0] = "Yellow";    // Allowed: ["Yellow", "Green", "Blue"]
// colors = ["New"];     // ❌ Error: can't reassign a const array

?️ Common Array Methods

These methods help you add, remove, and combine elements in arrays.

  • push() – Adds an element to the end.
  • pop() – Removes the last element.
  • shift() – Removes the first element.
  • unshift() – Adds an element to the beginning.
  • splice() – Adds/removes elements at a specific index.
  • slice() – Copies part of the array into a new one.
  • concat() – Merges two or more arrays.
  • join() – Converts an array to a string.
  • reverse() – Reverses the array in place.
? View Methods Example
let animals = ["Cat", "Dog"];
animals.push("Elephant");       // ["Cat", "Dog", "Elephant"]
animals.pop();                  // ["Cat", "Dog"]
animals.unshift("Lion");        // ["Lion", "Cat", "Dog"]
animals.shift();                // ["Cat", "Dog"]
let copy = animals.slice(1);    // ["Dog"]
let all = animals.concat(["Tiger"]); // ["Cat", "Dog", "Tiger"]

? Searching in Arrays

Use these methods to find values or check whether a value exists in an array.

  • indexOf() – Returns the first index of a value (or -1 if not found).
  • lastIndexOf() – Returns the last index of a value.
  • includes() – Returns true if the value exists.
  • find() – Returns the first element that matches a condition.
  • findIndex() – Returns the index of the first element that matches a condition.
? View Search Example
let nums = [5, 12, 8, 130, 44];
console.log(nums.indexOf(8));            // 2
console.log(nums.includes(130));         // true
let found = nums.find(n => n > 10);      // 12
let index = nums.findIndex(n => n > 100); // 3

↕️ Sorting Arrays

The sort() method converts elements to strings and sorts them alphabetically by default. For numbers, you should pass a compare function to get a correct numeric sort.

? View Sorting Example
let alpha = ["Banana", "Apple", "Mango"];
alpha.sort(); // ["Apple", "Banana", "Mango"]
let numbers = [4, 15, 2, 9];
numbers.sort();               // ["15", "2", "4", "9"] (alphabetical order!)
numbers.sort((a, b) => a - b); // [2, 4, 9, 15] (numeric sort)

? Array Iteration Methods

Iteration methods help you loop through arrays and create new arrays or values based on them.

  • forEach() – Runs a function for each item (does not return a new array).
  • map() – Transforms each item and returns a new array.
  • filter() – Returns a new array of items that match a condition.
  • reduce() – Reduces the array to a single value (like a sum).
? View Iteration Example
let nums = [1, 2, 3, 4, 5];
nums.forEach(n => console.log(n));          // Prints 1, 2, 3, 4, 5
let squares = nums.map(n => n * n);         // [1, 4, 9, 16, 25]
let evens = nums.filter(n => n % 2 === 0);  // [2, 4]
let total = nums.reduce((sum, n) => sum + n, 0); // 15

? Live Output and Explanation

For the nums array:

  • forEach() prints each number to the console.
  • map() produces a new array of squares: [1, 4, 9, 16, 25].
  • filter() returns only even numbers: [2, 4].
  • reduce() walks through the array and adds everything up, giving 15 as the final result.

None of these methods modify the original nums array, except forEach() if you explicitly change values inside it.

? Tips and Best Practices

  • Prefer const when declaring arrays, unless you really need to reassign the whole array.
  • Always provide a compare function when sorting numbers with sort().
  • Use map() for transforming arrays and filter() for selecting items.
  • Use reduce() for aggregations like sums, products, and building objects.
  • Remember: slice() creates a copy; it does not change the original array.
  • Use includes() for clean existence checks instead of comparing indexOf() to -1.

? Try It Yourself

  • Create an array of your favorite foods and practice: push(), pop(), shift(), unshift().
  • Take an array of numbers and use filter() to keep only even numbers, then map() them to their squares.
  • Use reduce() to find the sum of an array of numbers, then try finding the maximum value.
  • Create an array of strings and sort it alphabetically. Then create an array of numbers and practice sorting with and without a compare function.
  • Try using find() and findIndex() to locate the first number greater than a chosen value in an array.