Arrays in JavaScript โ concepts, types and usage.
Arrays in JavaScript โ concepts, types and usage. iti๐ Arrays in JavaScript โ Concepts, Types and Usage
An Array in JavaScript is a special type of object used to store multiple values in a single variable. Instead of declaring separate variables for each value, you can group them in an array for easier access and management. Arrays are commonly used in web development to store and manipulate lists of data.
๐ What is an Array?
A JavaScript array is a collection of elements (values), each with a numeric index starting from 0
.
let fruits = ["Apple", "Banana", "Mango"];
fruits[0]
returns"Apple"
fruits[1]
returns"Banana"
fruits[2]
returns"Mango"
๐ How to Declare an Array?
โ Using Array Literal (Preferred):
let colors = ["Red", "Green", "Blue"];
โ Using Array Constructor:
let numbers = new Array(10, 20, 30);
๐งช Types of Arrays in JavaScript
Though all arrays in JavaScript are of the same base type, we can classify them based on usage:
1. Homogeneous Arrays (Same data type)
let scores = [90, 80, 70];
2. Heterogeneous Arrays (Mixed data types)
let info = ["John", 25, true];
3. Multidimensional Arrays
let matrix = [
[1, 2],
[3, 4]
];
๐ ๏ธ Common Array Methods
Method | Description | Example |
---|---|---|
push() | Adds element at end | arr.push("New") |
pop() | Removes last element | arr.pop() |
shift() | Removes first element | arr.shift() |
unshift() | Adds element at start | arr.unshift("Start") |
length | Gives array size | arr.length |
indexOf() | Finds index of item | arr.indexOf("item") |
includes() | Checks if item exists | arr.includes("Apple") |
join() | Joins all elements | arr.join(", ") |
reverse() | Reverses order | arr.reverse() |
๐ Looping through an Array
โ Using for loop:
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
โ Using forEach method:
fruits.forEach(function(item) {
console.log(item);
});
๐ฏ Array Use Cases
- Storing user data (like names, scores, preferences)
- Managing dynamic lists (shopping cart, todo list)
- Form validations and batch data processing
- Real-time data updates in web applications
๐ Summary
- Arrays store multiple values in a single variable.
- They are indexed from
0
. - Support various methods to add, remove, and manipulate data.
- Useful for looping and batch operations.
JavaScript arrays are extremely versatile and form the backbone of dynamic data management in modern web development. ๐