Arrays are used to store multiple values in a single variable. They are one of the most important data structures in JavaScript and are widely used for managing lists of data such as names, numbers, or objects.
What is an Array
An array is a special variable that can hold more than one value at a time. Each value in an array is called an element, and each element has an index number starting from zero.
Why Use Arrays
Arrays help organize data efficiently
They allow you to store multiple values in one place
They make it easier to loop through data
They simplify data management in applications
How to Create an Array
You can create an array using square brackets
Example
let fruits = ["Apple", "Banana", "Mango"];
You can also create an empty array and add values later
let colors = [];
colors.push("Red");
colors.push("Blue");
Accessing Array Elements
Each element in an array has an index starting from zero
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]);
console.log(fruits[1]);
Modifying Array Elements
You can change values using their index
fruits[1] = "Orange";
Adding Elements to an Array
Use push to add elements at the end
fruits.push("Grapes");
Use unshift to add elements at the beginning
fruits.unshift("Pineapple");
Removing Elements from an Array
Use pop to remove the last element
fruits.pop();
Use shift to remove the first element
fruits.shift();
Array Length
You can check how many elements are in an array
console.log(fruits.length);
Looping Through an Array
You can use a loop to go through all elements
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Conclusion
Creating arrays in JavaScript is simple and essential for handling multiple values. Arrays make your code more organized and efficient, especially when working with lists of data in real world applications.