JavaScript Arrays
Store ordered lists and transform them with array methods.
Arrays are one of the most useful data structures in JavaScript. They allow you to store multiple values in a single variable, making it easier to manage and work with collections of data.
Imagine an online store that sells hundreds of products. Instead of creating a separate variable for each product, you can store all product names inside a single array. This makes your code cleaner, more organized, and easier to maintain.
Arrays are commonly used in almost every JavaScript application, from simple websites to complex web applications.
What Is an Array?
An array is a special type of variable that can hold multiple values in a single container.
Instead of creating separate variables:
let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";You can store all values inside an array:
let fruits = ["Apple", "Banana", "Mango"];This approach is much more efficient and easier to manage.
Creating an Array
Arrays are created using square brackets.
let colors = ["Red", "Green", "Blue"];An array can contain different types of data.
let data = ["John", 25, true];Although JavaScript allows mixed data types, it is generally better to store similar types of data together.
Accessing Array Elements
Each item in an array has a position called an index.
Array indexes start from 0, not 1.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]);Output:
AppleHere:
- fruits[0] returns Apple
- fruits[1] returns Banana
- fruits[2] returns Mango
Adding and Removing Elements
Adding Elements
Use the push() method to add an item to the end of an array.
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);Output:
["Apple", "Banana", "Mango"]Removing Elements
Use the pop() method to remove the last item.
fruits.pop();
console.log(fruits);Output:
["Apple", "Banana"]Looping Through an Array
Arrays are often used with loops.
let fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}Output:
Apple
Banana
MangoThis allows JavaScript to process every item in the array automatically.
Useful Array Methods
length
Returns the number of items in an array.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.length);Output:
3includes()
Checks whether an item exists in an array.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Banana"));Output:
trueKey Takeaways
- Arrays is an important topic to understand.
- Start with small examples and practice one step at a time.
- Use the idea in simple projects so it becomes easier to remember.