Introduction to Arrays in JavaScript
Looping through an array using for loop and forEach in JavaScript
Arrays are one of the most commonly used data structures in JavaScript. They allow you to store multiple values in a single variable, making it easy to organize and manipulate collections of data.
In this tutorial, we'll cover the basics of arrays, how to create them, access elements, and use common methods.
An array is a special variable that can hold more than one value at a time. Values in an array are ordered and indexed starting from 0.
const fruits = ["apple", "banana", "cherry"];
fruits[0]
returns "apple"
fruits[1]
returns "banana"
You can create arrays in two main ways:
const numbers = [1, 2, 3, 4, 5];
const cars = new Array("Toyota", "BMW", "Tesla");
You access an array element by referring to its index:
const colors = ["red", "green", "blue"];
console.log(colors[1]); // Output: green
colors[0] = "yellow"; // Changes "red" to "yellow"
The length
property returns the number of elements in an array:
console.log(colors.length); // Output: 3
Here are some useful built-in methods to work with arrays:
push()
- Adds element to the endcolors.push("purple");
pop()
- Removes the last elementcolors.pop();
shift()
- Removes the first elementcolors.shift();
unshift()
- Adds element to the beginningcolors.unshift("pink");
indexOf()
- Finds the index of an elementcolors.indexOf("blue");
includes()
- Checks if value existscolors.includes("green");
You can loop through arrays using:
for
loop:for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
forEach()
method:fruits.forEach(function(item) {
console.log(item);
});
Arrays are a fundamental concept in JavaScript. They help manage and process lists of data efficiently. As you grow in your JavaScript journey, mastering arrays will allow you to build more dynamic and powerful web applications.
In the next tutorials, we’ll dive into array methods like map, filter, reduce, and how to work with multi-dimensional arrays.