Skip to main content
JavaScript Basics
CHAPTER 10 Beginner

JavaScript Arrays

Updated: May 12, 2026
25 min read

# JavaScript Arrays

Imagine you are managing a classroom of 30 students. If you create a separate variable for every single student (let student1 = "John"; let student2 = "Alice";), your code will become a massive, unreadable mess.

This is where Arrays come in. An array is a special variable that can hold more than one value at a time.

1. Introduction

An array is an ordered list of values. You can store strings, numbers, booleans, and even functions or other arrays inside an array. Once you have your data grouped in an array, JavaScript gives you powerful tools (called "methods") to sort, filter, add, and remove items easily.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Create arrays using the array literal syntax [].
  • Access and modify specific items in an array using an index.
  • Use basic array methods: push(), pop(), shift(), and unshift().
  • Use advanced array iteration methods: map() and filter().
  • Build a working Todo List application using arrays.

3. Creating an Array

The easiest and most common way to create an array is using square brackets [], separating items with commas. This is called an Array Literal.

javascript
12
// Syntax
const arrayName = [item1, item2, item3];

*Note: We usually declare arrays with const. The items inside the array can still be changed, but the array itself cannot be completely overwritten with a non-array value.*

4. Accessing Array Elements

You access an array element by referring to its Index Number. CRITICAL RULE: In JavaScript (and most programming languages), arrays are zero-indexed. The first item is at index 0, the second item is at index 1, and so on.

javascript
123
// Example
const cars = ["Volvo", "BMW", "Toyota"];
console.log(cars[0]); // Output: Volvo

5. Array Length

Every array has a built-in property called length that tells you exactly how many items are inside it.

javascript
123
// Example
const fruits = ["Apple", "Banana", "Orange"];
console.log(fruits.length); // Output: 3

---

6. Real-world Examples & Code Snippets

Example 1: Creating and Accessing

javascript
1234
// Example JavaScript
const students = ["Emily", "David", "Sarah"];
console.log("First Student: " + students[0]); // Emily
console.log("Last Student: " + students[2]);  // Sarah

Example 2: Changing an Array Element

You can overwrite a specific item by targeting its index.

javascript
12345
// Example JavaScript
const colors = ["Red", "Blue", "Green"];
colors[1] = "Yellow"; // Overwrite Blue with Yellow

console.log(colors); // Output: ["Red", "Yellow", "Green"]

Example 3: Mixed Data Types

An array can hold different types of data, though it's usually best to keep similar data together.

javascript
123
// Example JavaScript
const userProfile = ["Alex", 25, true, null];
console.log(userProfile[1]); // Output: 25

Example 4: push() - Add to End

The push() method adds a new item to the end of an array.

javascript
12345
// Example JavaScript
const inventory = ["Sword", "Shield"];
inventory.push("Health Potion");

console.log(inventory); // Output: ["Sword", "Shield", "Health Potion"]

Example 5: pop() - Remove from End

The pop() method removes the last item from an array and returns it.

javascript
123456
// Example JavaScript
const numbers = [1, 2, 3, 4];
let removedNum = numbers.pop();

console.log(numbers);    // Output: [1, 2, 3]
console.log(removedNum); // Output: 4

Example 6: unshift() - Add to Beginning

The unshift() method adds a new item to the beginning of an array.

javascript
12345
// Example JavaScript
const queue = ["Alice", "Bob"];
queue.unshift("VIP User");

console.log(queue); // Output: ["VIP User", "Alice", "Bob"]

Example 7: shift() - Remove from Beginning

The shift() method removes the first item from an array (shifting all other items down one index).

javascript
123456
// Example JavaScript
const waitingRoom = ["Patient A", "Patient B"];
let nextUp = waitingRoom.shift();

console.log(waitingRoom); // Output: ["Patient B"]
console.log(nextUp);      // Output: Patient A

Example 8: Looping Through an Array

The classic way to go through every item in an array is using a for loop combined with the .length property.

javascript
123456
// Example JavaScript
const animals = ["Cat", "Dog", "Bird"];

for (let i = 0; i < animals.length; i++) {
    console.log("I love my " + animals[i]);
}

Example 9: The map() Method (Advanced)

map() creates a brand new array by performing a function on every item in the original array. This is extremely powerful in modern JS (like React).

javascript
123456789
// Example JavaScript
const prices = [10, 20, 30];

// Double every price
const doubledPrices = prices.map(function(price) {
    return price * 2;
});

console.log(doubledPrices); // Output: [20, 40, 60]

Example 10: The filter() Method (Advanced)

filter() creates a brand new array containing only the items that pass a specific test.

javascript
123456789
// Example JavaScript
const ages = [15, 22, 12, 30, 18];

// Keep only ages 18 and up
const adults = ages.filter(function(age) {
    return age >= 18; // Must return a boolean
});

console.log(adults); // Output: [22, 30, 18]

---

7. Common Mistakes for Beginners

  1. 1. Forgetting Zero-Index: If an array has 3 items, trying to access array[3] will return undefined! The highest index is 2 (0, 1, 2).
  1. 2. Writing over the length: const arr = ["A"]; arr[5] = "B"; This creates "empty holes" in your array for indices 1, 2, 3, and 4.
  1. 3. Using console.log(array) for users: The console formats arrays nicely. If you output an array directly to HTML innerHTML, it prints out as comma-separated text which is usually ugly. You need to loop through it to build HTML.

8. Best Practices

  • Always declare arrays with const. It prevents you from accidentally overwriting the entire array with a string or number later.
  • Use push() instead of array[array.length] = "new item" to add items.
  • Modern JavaScript developers prefer map() and filter() over writing raw for loops because it results in cleaner, more readable code.

9. Mini Project: Interactive Todo List

Let's build a simple Todo list using arrays to store our data, and a loop to update the HTML.

HTML:

html
12345678910111213141516171819202122232425262728
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: sans-serif; padding: 20px;}
        .todo-app { width: 300px; padding: 20px; background: #fff; border: 1px solid #ccc; box-shadow: 2px 2px 10px rgba(0,0,0,0.1); }
        ul { list-style-type: none; padding: 0; }
        li { padding: 8px; background: #eee; margin-bottom: 5px; border-radius: 4px; }
        input { padding: 8px; width: 65%; }
        button { padding: 8px; width: 25%; background: #28a745; color: white; border: none; cursor: pointer;}
    </style>
</head>
<body>

    <div class="todo-app">
        <h2>My Tasks</h2>
        <input type="text" id="taskInput" placeholder="Add a task...">
        <button onclick="addTask()">Add</button>
        
        <ul id="taskList"></ul>
        <button onclick="removeLast()" style="width:100%; margin-top:10px; background:#dc3545;">Remove Last</button>
    </div>

    <script src="todo.js"></script>
</body>
</html>

todo.js:

javascript
1234567891011121314151617181920212223242526272829303132333435363738
// Example JavaScript

// 1. Create our master data array
const myTodos = ["Buy Milk", "Read Book"];

// 2. A function to display the array on screen
function renderList() {
    let listElement = document.getElementById("taskList");
    let htmlContent = "";
    
    // Loop through the array and build HTML strings
    for (let i = 0; i < myTodos.length; i++) {
        htmlContent += "<li>" + myTodos[i] + "</li>";
    }
    
    listElement.innerHTML = htmlContent;
}

// 3. Function to add a task
function addTask() {
    let input = document.getElementById("taskInput");
    let newTask = input.value;
    
    if (newTask !== "") {
        myTodos.push(newTask); // Add to end of array
        input.value = ""; // Clear the input box
        renderList(); // Refresh the screen
    }
}

// 4. Function to remove last task
function removeLast() {
    myTodos.pop(); // Remove from end of array
    renderList(); // Refresh the screen
}

// Render the list when the page first loads
renderList();

10. Exercises

  1. 1. Create an array called movies with 3 of your favorite movies. Console log the second movie in the array.
  1. 2. Use the push() method to add a 4th movie to your array.
  1. 3. Write a for loop that iterates through your movies array and console logs each one.

11. MCQs (Multiple Choice Questions)

Q1: What is the correct syntax for creating an array? A) const arr = "A", "B", "C"; B) const arr = (A, B, C); C) const arr = ["A", "B", "C"]; D) const arr = {"A", "B", "C"}; *Answer: C*

Q2: What is the index of the first item in an array? A) 0 B) 1 C) -1 D) It depends on the array length. *Answer: A*

Q3: Which method removes the LAST element from an array? A) shift() B) unshift() C) push() D) pop() *Answer: D*

12. Interview Questions

Q: What is the difference between push() and unshift()? *A: Both methods add elements to an array. push() adds elements to the end of the array, while unshift() adds elements to the beginning of the array, shifting the existing elements to higher indexes.*

Q: Do map() and filter() modify the original array? *A: No, map() and filter() are pure functions. They do not mutate the original array; instead, they return a brand new array containing the transformed or filtered items.*

13. FAQs

Q: Can I put arrays inside of arrays? *A: Yes! This is called a Multidimensional Array. Example: const grid = [[1, 2], [3, 4]];. You access them like a grid: grid[0][1] returns 2.*

14. Summary

  • Arrays store multiple values in a single variable.
  • Arrays are zero-indexed (arr[0]).
  • Use .length to find out how many items are in an array.
  • Methods: push() (add end), pop() (remove end), unshift() (add start), shift() (remove start).
  • Use for loops, map(), or filter() to iterate over arrays.

15. Next Chapter Recommendation

Arrays are great for lists of *similar* things. But what if we want to store detailed information about a single thing? Like a User with a name, age, and email? In the next chapter, JavaScript Objects, we will learn how to create structured data entities.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·