Introduction
An array is one of the most useful data structures in JavaScript. It allows us to store multiple values in a single variable instead of creating separate variables for each value. Arrays make it easier to organize, access, and manipulate collections of data.
What is an Array?
An array is a special type of object that stores multiple values in an ordered list. Each value in an array is called an element, and every element has an index. The index always starts from 0.
Syntax
let fruits = ["Apple", "Banana", "Mango"];
In the above example:
-
Appleis at index0 -
Bananais at index1 -
Mangois at index2
Accessing Array Elements
You can access any element by using its index.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Mango
Updating an Array Element
You can change an existing element by assigning a new value.
let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange";
console.log(fruits);
Output:
["Apple", "Orange", "Mango"]
Finding the Length of an Array
The length property returns the total number of elements in an array.
let numbers = [10, 20, 30, 40];
console.log(numbers.length);
Output:
4
Common Array Methods
1. push()
Adds an element to the end of the array.
let colors = ["Red", "Blue"];
colors.push("Green");
console.log(colors);
2. pop()
Removes the last element.
let colors = ["Red", "Blue", "Green"];
colors.pop();
console.log(colors);
3. unshift()
Adds an element to the beginning.
let colors = ["Blue", "Green"];
colors.unshift("Red");
console.log(colors);
4. shift()
Removes the first element.
let colors = ["Red", "Blue", "Green"];
colors.shift();
console.log(colors);
5. indexOf()
Returns the index of an element.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.indexOf("Banana"));
6. includes()
Checks whether an element exists in the array.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Mango"));
Looping Through an Array
A for loop is commonly used to access every element.
let numbers = [10, 20, 30, 40];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
Real-Life Example
Suppose a school wants to store student names. Instead of creating many variables, we can use an array.
let students = ["Rahul", "Priya", "John"];
students.push("Anu");
for (let i = 0; i < students.length; i++) {
console.log(students[i]);
}
Advantages of Arrays
- Store multiple values in a single variable.
- Easy to access using indexes.
- Reduce code repetition.
- Support many built-in methods for data manipulation.
- Improve code readability and efficiency.
Conclusion
Arrays are an essential part of JavaScript programming. They help developers store, organize, and manipulate collections of data efficiently. By learning arrays and their methods, you can solve many programming problems more easily and write cleaner, more efficient code.
Top comments (0)