JavaScript Arrays and Loops for Beginners
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.
⚠️ 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.
✅ 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.
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.
🎯 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.
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.
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