What Are Arrays?
An array is used to store multiple values in a single variable.
For example, if we want to store the names of five fruits, we don't need to create five separate variables. We can store all the names in one array.
let fruits = ["Apple", "Banana", "Mango", "Orange"];
Here, fruits is an array containing four items.
1. Accessing Array Elements
We can access array elements using their index.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]);
console.log(fruits[1]);
Output:
Apple
Banana
Remember that array indexing starts at 0, not 1.
-
fruits[0]gives the first element. -
fruits[1]gives the second element. -
fruits[2]gives the third element.
2. Adding Elements
JavaScript provides methods to add new elements to an array.
Using push(): Adds an element to the end.
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);
Output: ["Apple", "Banana", "Mango"]
Using unshift(): Adds an element to the beginning.
fruits.unshift("Orange");
console.log(fruits);
Now, "Orange" becomes the first element.
3. Removing Elements
We can remove elements using different methods.
Using pop(): Removes the last element.
let fruits = ["Apple", "Banana", "Mango"];
fruits.pop();
console.log(fruits);
Output: ["Apple", "Banana"]
Using shift(): Removes the first element.
fruits.shift();
console.log(fruits);
Now, "Apple" is removed from the array.
4. Finding the Length of an Array
The length property tells us how many elements an array contains.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.length);
Output: 3
This is useful when we want to know how many items are stored in an array.
5. Looping Through Arrays
We can use loops to access each element of an array.
let fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
This prints each fruit on a separate line.
Loops are useful when working with lists of products, students, or other data.
6. Useful Array Methods
JavaScript provides several methods to work with arrays.
-
push()— adds an element at the end. -
pop()— removes the last element. -
shift()— removes the first element. -
unshift()— adds an element at the beginning. -
includes()— checks whether an array contains a value. -
indexOf()— finds the first index of a value, or returns-1if it is not found.
Example:
let numbers = [10, 20, 30];
console.log(numbers.includes(20));
console.log(numbers.indexOf(30));
Output:
true
2
Why Are Arrays Important?
Arrays help us:
- Store multiple values together.
- Manage lists of products or student records.
- Loop through collections of data.
- Add and remove items easily.
- Build applications such as shopping carts and product management systems.
Top comments (1)
The length property of an array actually tells you how many slots are in the array, not how many elements it contains. These are often the same value, but not always.