JavaScript Arrays
Imagine you are building a grocery list app. Without arrays, you would have to create a separate variable for every single item: let item1 = "Apple"; let item2 = "Bread"; let item3 = "Milk";. This quickly becomes impossible to manage.
Arrays solve this by allowing you to store a collection of data under a single variable name.
What are Arrays and Why Do We Need Them?
An array is a special type of object in JavaScript used to store multiple values in a single ordered list.
We need them because they:
Organize data: Group related items together.
Are Dynamic: They can grow or shrink as you add or remove items.
Provide Order: Every item has a specific position, making it easy to sort or search.
How to Create an Array
The most common way to create an array is using square brackets []. This is called the "Array Literal" syntax.
let arr = new Array();
let arr = [23 , 45, 56];
Accessing Elements Using Index
In JavaScript, arrays are zero-indexed. This means the counting starts at 0, not 1.
The 1st item is at index
0.The 2nd item is at index
1.
let fruits = ["Apple", "Orange", "Plum"];
console.log( fruits[0] ); // Apple
Updating Elements
Arrays are mutable, meaning you can change the values inside them even if the array was declared with const. To update a value, simply target its index and assign a new value.
let fruits = ["Apple", "Orange", "Plum"];
fruits[1] = "Mango";
console.log( fruits[1] ); // Mango
The Array Length Property
The .length property tells you exactly how many elements are currently in the array. This is extremely useful for knowing where an array ends.
let arr = ["hn" , "nijnfq" , "njnjq"];
console.log(arr.length);
Note - You can always find the last item of any array by using array[array.length - 1].
Basic Looping Over Arrays
Looping allows you to perform an action on every single item in the array without writing repetitive code.
let arr = ["english" , "math", "hindi"];
for(let i=0; i<arr.length; i++){
console.log(arr[i]);
}
//english
// math
// hindi
The for..of loop does not give access to number of current element , just its value , but in most cases that's enough and it is shorter.
for(let subject of arr){
console.log(subject);
}
As array are also objects we can loop over it through for...in
for(let subject in arr){
console.log(arr[subject]);
}
But there are some problems with array like objects. Those contains extra properties like length etc , which we usually don't need.