Start learning free

LESSON 96 OF 410 · ARRAYS I

Arrays in JavaScript

Lesson Read the full explanation

When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.

In JavaScript, we use arrays to store several pieces of data in one place.


Array Declaration / Creation:

You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:

let sandwich = ["peanut butter", "jelly", "bread"]

In this program we created an array consisting of 3 string items: "peanut butter", "jelly" and "bread".

Then, we stored that array in a variable sandwich so we can later access it. For example, I can print the array:

// Creating the array:
let sandwich = ["peanut butter", "jelly", "bread"];

// Printing the array:
console.log(sandwich); // Output: ["peanut butter", "jelly", "bread"]

Items Data Types

Arrays can store any data types (strings, integers, booleans, etc.) and the items shouldn't necessary be of the same data type. For example:

let myArray = ["Hello world!", 32, False];

myArray consits of one string item, one number item and one boolean item.

We use arrays to better organize pieces of data which are part of the same family or share the same meaning, like the name of our friends or the items in a sandwich.

So most of the time we will have arrays where the items share the same data type.


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    JAVASCRIPT · ARRAYS I

    Arrays in JavaScript, explained

    JavaScript Arrays: Store and Manage Collections of Data

    Every meaningful JavaScript application works with collections of things — a list of users, an array of prices, a set of messages. The array is JavaScript's built-in ordered collection, and it's the first data structure you'll reach for in almost every real project. Master arrays and you unlock loops, filtering, sorting, and the entire world of array methods that make JavaScript powerful.

    Creating and Accessing Arrays

    Wrap values in square brackets. Access any element by its zero-based index:

    // Create an array:
    const scores = [95, 82, 74, 88, 91];
    
    // Access by index (0-based):
    console.log(scores[0]);   // 95 (first)
    console.log(scores[4]);   // 91 (fifth)
    console.log(scores[scores.length - 1]);  // 91 (last)
    
    // Arrays can mix types:
    const user = ["Alice", 28, true, null];
    console.log(user[0]);   // "Alice"
    console.log(user[1]);   // 28
    

    Modifying Arrays

    JavaScript arrays are mutable — change, add, and remove elements freely:

    const tasks = ["Design", "Build", "Test"];
    
    // Change an element:
    tasks[1] = "Develop";
    console.log(tasks);   // ["Design", "Develop", "Test"]
    
    // Add to the end:
    tasks.push("Deploy");
    console.log(tasks);   // ["Design", "Develop", "Test", "Deploy"]
    
    // Remove from the end:
    const removed = tasks.pop();
    console.log(removed);  // "Deploy"
    console.log(tasks);    // ["Design", "Develop", "Test"]
    
    // Add to the front:
    tasks.unshift("Plan");
    console.log(tasks);   // ["Plan", "Design", "Develop", "Test"]
    
    // Remove from the front:
    tasks.shift();
    console.log(tasks);   // ["Design", "Develop", "Test"]
    

    Essential Array Properties and Methods

    • array.length — number of elements
    • array.push(x) — add to end; returns new length
    • array.pop() — remove and return last element
    • array.unshift(x) — add to front
    • array.shift() — remove and return first element
    • array.includes(x) — check if x exists (returns true/false)
    • array.indexOf(x) — find first index of x (-1 if not found)
    • array.slice(start, end) — extract a sub-array (non-destructive)
    • array.splice(start, n) — remove n elements at start (destructive)

    The Power of Array Methods: map, filter, reduce

    These three methods are what make JavaScript arrays so expressive. They transform arrays without manual loops:

    const prices = [29.99, 14.50, 89.99, 5.00, 45.00];
    
    // filter — keep only items matching a condition:
    const affordable = prices.filter(p => p < 30);
    console.log(affordable);   // [29.99, 14.50, 5.00]
    
    // map — transform every element:
    const withTax = prices.map(p => +(p * 1.08).toFixed(2));
    console.log(withTax);   // [32.39, 15.66, 97.19, 5.40, 48.60]
    
    // reduce — fold down to a single value:
    const total = prices.reduce((sum, p) => sum + p, 0);
    console.log(total.toFixed(2));   // "184.48"
    

    Real-World Example: Processing a List of Users

    const users = [
      { name: "Alice", age: 28, premium: true },
      { name: "Bob",   age: 17, premium: false },
      { name: "Carol", age: 32, premium: true },
      { name: "Dan",   age: 15, premium: false },
    ];
    
    // Get premium adult users:
    const eligible = users.filter(u => u.premium && u.age >= 18);
    console.log(eligible.map(u => u.name));   // ["Alice", "Carol"]
    
    // Get all names:
    const names = users.map(u => u.name);
    console.log(names);   // ["Alice", "Bob", "Carol", "Dan"]
    

    Common Mistakes to Avoid

    • Off-by-one: Last valid index is length - 1. Accessing arr[arr.length] returns undefined, not an error.
    • Mutating when you meant to copy: arr2 = arr1 gives you a reference, not a copy. Use [...arr1] or arr1.slice() to copy.
    • Confusing push return value: push() returns the new array length, not the array itself.
    const a = [1, 2, 3];
    
    // Reference vs. copy:
    const b = a;         // b points to the same array
    b.push(4);
    console.log(a);      // [1, 2, 3, 4]  — a was modified too!
    
    const c = [...a];    // c is a shallow copy
    c.push(5);
    console.log(a);      // [1, 2, 3, 4]  — a is unchanged
    console.log(c);      // [1, 2, 3, 4, 5]
    

    Key Takeaways

    • Create arrays with square brackets; access elements with zero-based indices.
    • push()/pop() for the end; unshift()/shift() for the front.
    • Use map(), filter(), and reduce() for clean, expressive data transformations.
    • Copying an array requires [...arr] or .slice() — assignment just copies the reference.

    What to Learn Next

    With arrays mastered, explore for...of loops for clean iteration, array destructuring for pulling out values elegantly, and the spread operator for combining arrays. Then dive into objects — JavaScript's other fundamental data structure — and see how arrays of objects power real-world data handling.

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free