Ad space (banner)
🟨JavaScript Lessons
Lesson 6 / 69

Working with Arrays

In this lesson you'll learn the basics of using arrays in JavaScript so you can handle multiple pieces of data together efficiently. This is aimed at people searching "JavaScript array usage" or "JavaScript forEach for beginners."

An array is a box that can hold multiple pieces of data together. You create one with [ ], check its size with .length, and process its contents with a for loop or various methods. If you tried to handle 100 names using "one variable per value," you'd need to create 100 separate variables — not realistic at all. An array lets you manage all that data together in a single variable.

The sample code creates an array called fruits, gets its element count with .length, and processes each element one at a time with .forEach(). The pattern .forEach((item, index) => { ... }) is commonly used any time you want to run the same processing on every element of an array — it's a way of thinking you'll also see with .map() and .filter(), which you'll learn about later.

A common beginner stumbling block is that array indexes start at 0. fruits[1] refers to the *second* element, and that gap between "1st = fruits[0]" and everyday counting is a common source of bugs. Also be careful: accessing an index that doesn't exist doesn't throw an error — it just returns undefined.

In real development, data that comes in multiple items — a product list, a list of user comments — is almost always handled as an array. Data received from a database or API is also frequently in array form, so getting comfortable with array operations is basically the foundational fitness of web development.

Arrays also come with methods like .push() to add an element to the end and .pop() to remove the last element. Combining these basic methods lets you easily implement operations you see in real apps all the time, like adding an item to a shopping cart.

When you want to remove an element from an array, or insert one at a specific position, you use .splice() for both. It's a method with slightly involved arguments, but it comes up often whenever you need to edit the middle of an array, so it's worth remembering the name even if you don't master it right away.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)