Course Lessons

JAVASCRIPT FOUNDATIONS + AI MINDSET

Back to Course

JavaScript Arrays and Loops for Beginners

JAVASCRIPT... Lesson 6 of 41 9 min

Arrays and Loops

Storing Data, Iterating, and Transforming Collections

By AI Learning Assistant  ·  JavaScript  ·  ES6  ·  Fundamentals

🤖 AI-POWERED LESSON

This article is paired with a live AI session. As you read, you will see real questions asked to an AI assistant and the answers that came back, showing you exactly how to use AI to master JavaScript arrays and iteration faster.

An array is an ordered list of values. Unlike variables that hold a single value, arrays can store hundreds, thousands, or millions of items under one name. Every item gets a numeric index starting from zero, allowing you to access, modify, and process data in a predictable sequence.

Arrays are the backbone of almost every JavaScript application. A to-do list is an array of tasks. A shopping cart is an array of products. A chat history is an array of messages. Learning to create, populate, traverse, and transform arrays is not optional; it is the core skill that separates beginners from productive developers.

We will cover array creation and indexing, the essential methods for adding and removing elements, the three powerhouse iteration methods forEach, map, and filter, plus traditional loops for scenarios where you need granular control. At each stage, AI will clarify the patterns that make your code clean and efficient.

By the end, you will build a student roster, transform it with .map(), and understand exactly when to reach for each iteration tool.

Creating and Accessing Arrays

LITERAL SYNTAX · ZERO-BASED INDEXING · LENGTH PROPERTY

You create an array using square brackets. Items are separated by commas. You can store any type of value in an array: strings, numbers, booleans, objects, even other arrays. Arrays in JavaScript are dynamic; they grow and shrink automatically as you add or remove elements.

Accessing elements uses bracket notation with a zero-based index. The first item is at index 0, the second at index 1, and so on. The .length property tells you how many items exist. The last item is always at index length - 1.

const students = [ "Kemi" , "Tunde" , "Amara" , "Chidi" , "Zara" ]; console . log ( students [ 0 ]); // "Kemi" console . log ( students . length ); // 5

⚠️ THE OFF-BY-ONE ERROR

Because indexing starts at zero, the last element is at length - 1, not length. Accessing students[5] on a five item array returns undefined. This is the most common array mistake for beginners.

Adding and Removing Elements

PUSH · POP · SHIFT · UNSHIFT · SPLICE

Arrays are mutable. .push() adds to the end. .pop() removes from the end. .unshift() adds to the beginning. .shift() removes from the beginning. These four methods form the core toolkit for managing array contents.

Operations at the end of an array are fast because the engine simply increments the length. Operations at the beginning are slow because every existing element must shift its index. For large arrays, avoid .unshift() and .shift() in performance critical code.

students . push ( "Emeka" ); // Add to end console . log ( students ); console . log ( "Total students: " + students . length ); // 6

✅ SPLICE FOR MIDDLE OPERATIONS

When you need to insert or delete elements from the middle, use .splice(startIndex, deleteCount, ...itemsToAdd). It modifies the original array and returns the removed elements. For removing without adding, pass zero as the second argument.

forEach: Side Effects

ITERATION · NO RETURN · INDEX ACCESS

The .forEach() method executes a provided function once for each array element. It is the most direct way to say "do something with every item." The callback receives three arguments: the current element, its index, and the entire array.

Crucially, .forEach() always returns undefined. It is designed for side effects: logging to the console, updating the DOM, or sending network requests. If you need to create a new array from the results, .forEach() is the wrong tool.

students . forEach (( student , index ) => { console . log (( index + 1 ) + ". " + student + " is enrolled in JS Mastery" }); // 1. Kemi is enrolled in JS Mastery // 2. Tunde is enrolled in JS Mastery ...

map: Transformation

NEW ARRAY · SAME LENGTH · PURE FUNCTION

The .map() method creates a new array populated with the results of calling a provided function on every element. It does not modify the original array. The output array always has the same length as the input array.

This is the transformation tool. You use it when you have an array of one thing and need an array of another thing. Converting prices to formatted strings. Extracting IDs from objects. Adding prefixes to names. If your callback returns a value, .map() collects it into the new array.

const cohort = students . map ( s => s + " - Cohort 01" ); console . log ( cohort ); // ["Kemi - Cohort 01", ...]

🎯 IMMUTABILITY PRINCIPLE

Because .map() returns a new array, your original data remains untouched. This is the foundation of functional programming in JavaScript. You can chain .map() with .filter() and .sort() without worrying about corrupting your source data.

filter: Subsetting

CONDITIONAL SELECTION · BOOLEAN RETURN · NEW ARRAY

The .filter() method creates a new array with all elements that pass the test implemented by the provided function. The callback must return a boolean. If it returns true, the element is included in the result. If false, it is discarded.

The output array may be shorter than the input. It may even be empty. Like .map(), .filter() does not modify the original array. You use it when you need a subset: active users, completed tasks, products in stock.

const longNames = students . filter ( s => s . length > 4 ); console . log ( longNames ); // ["Tunde", "Amara", "Chidi"]

Traditional Loops

FOR · WHILE · DO WHILE · BREAK · CONTINUE

Before array methods became standard, developers used for loops. A for loop gives you explicit control over initialization, condition, and increment. This is useful when you need to skip elements, iterate backwards, or break out early based on a complex condition.

The break statement exits the loop immediately. The continue statement skips the rest of the current iteration and moves to the next. These give you precision that array methods cannot match, though they often make code harder to read.

for ( let i = 0 ; i < students . length ; i ++) { console . log ( students [ i ]); }

LIVE AI LEARNING SESSION

Ask your AI assistant this question ↓

💬 YOU ASK THE AI:

"Explain the difference between forEach, map, and filter in JavaScript arrays with one real example each. Then show me how to use .map() to create a new array that adds ' - Cohort 01' to each student name."

🤖 AI RESPONDS:

These three methods are the holy trinity of array iteration, but they serve fundamentally different purposes. Choosing the wrong one is a common source of bugs and confusion.

forEach is for side effects. It walks through the array and lets you do something with each item, like logging or updating the DOM. It returns nothing. Think of it as a delivery driver dropping off packages; the driver does not create anything new, they just distribute what exists.

map is for transformation. It walks through the array and creates a new array where every item has been changed by your callback. The original array stays untouched. Think of it as a factory assembly line; every input item comes out modified on the other side.

filter is for selection. It walks through the array and creates a new array containing only the items that pass your test. Think of it as a bouncer at a club; some items get in, others are rejected.

The cohort exercise: You need to transform every name, not filter them and not just log them. .map() is the perfect tool because it produces a new array of the same length where every element has been modified.

Apply it: cohort mapping

const cohort = students . map ( name => name + " - Cohort 01" ); // Result: // ["Kemi - Cohort 01", // "Tunde - Cohort 01", // "Amara - Cohort 01", ...]

📝 MY NOTE — IN MY OWN WORDS

The AI analogies finally made this stick. I now see forEach as a delivery driver, map as a factory line, and filter as a club bouncer. I built the student roster and used .forEach() to print enrollment messages with their index numbers. Then I used .map() to create the cohort array without touching the original. The immutability principle is huge; I now understand why professional code never modifies source data directly. I also learned that .push() is fast at the end but .unshift() is slow at the beginning because of index shifting. Going forward, I will always ask: am I transforming? Use map. Am I selecting? Use filter. Am I just doing something? Use forEach. And I will prefer array methods over for loops unless I absolutely need to break early or control the iteration manually.

Quick Comparison

FEATURE forEach map filter
Purpose Side effects (logging, DOM) Transform every element Select matching elements
Return value undefined New array (same length) New array (shorter or equal)
Modifies original? ❌ No (unless you do it) ❌ No ❌ No
Callback return type Ignored Any value (becomes element) Boolean (true = keep)
Chainable? ❌ No (returns undefined) ✅ Yes ✅ Yes
Best analogy Delivery driver Factory assembly line Club bouncer

🤖 HOW AI ACCELERATES THIS TOPIC

Stuck on whether to use map or forEach? Paste your code into an AI and ask: "Should I use map, filter, or forEach here, and why?" The AI will analyze your intent and suggest the cleanest pattern.

You can also ask: "Chain map and filter to get active users with formatted names." The AI will compose the chain and explain the order of operations.

For performance questions, ask: "When should I use a for loop instead of array methods?" The AI will explain that modern engines optimize methods well, but for loops still win when you need early termination or massive datasets.

AI-Assisted JavaScript Learning · Arrays & Iteration · JavaScript ES6+

Complete this lesson

Mark as complete to track your progress