In JavaScript, an array is a special variable used to store multiple values in a single variable.
1. How to create an array
let fruits = ["Apple", "Mango", "Orange", "Banana"];
console.log(fruits);
Output:
["Apple", "Mango", "Orange", "Banana"]
2. Access array elements
Array indexing starts from 0, not 1.
l
let fruits = ["Apple", "Mango", "Orange", "Banana"];
console.log(fruits[0]); // Apple
console.log(fruits[1]); // Mango
console.log(fruits[2]); // Orange
console.log(fruits[3]); // Banana
3. Important array properties and methods
let fruits = ["Apple", "Mango", "Orange"];
console.log(fruits.length);
Output: 3
push() — add an element at the end
let fruits = ["Apple", "Mango"];
fruits.push("Orange");
console.log(fruits);
Output: ["Apple", "Mango", "Orange"]
pop() — remove the last element
let fruits = ["Apple", "Mango", "Orange"];
fruits.pop();
console.log(fruits);
Output: ["Apple", "Mango"]
unshift() — add an element at the beginning
let fruits = ["Mango", "Orange"];
fruits.unshift("Apple");
console.log(fruits);
Output: ["Apple", "Mango", "Orange"]
shift() — remove the first element
let fruits = ["Apple", "Mango", "Orange"];
fruits.shift();
console.log(fruits);
Output: ["Mango", "Orange"]
4. Update an array element
let fruits = ["Apple", "Mango", "Orange"];
fruits[1] = "Banana";
console.log(fruits);
Output:["Apple", "Banana", "Orange"]
The element at index 1 changes from "Mango" to "Banana".
5. Loop through an array
Use a for loop to access every element.
let fruits = ["Apple", "Mango", "Orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output :
Apple
Mango
Orange
-
forEach()— execute code for each element
let fruits = ["Apple", "Mango", "Orange"];
fruits.forEach(function(fruit) {
console.log(fruit);
});
This prints every fruit without manually managing the index.
-
map()— create a new array A JavaScript Map is an object that can store collections of key-values
let numbers = [10, 20, 30, 40];
let result = numbers.map(function(num) {
return num * 2;
});
console.log(result);
plaintext
Output : [20, 40, 60, 80]
-
filter()— select elements that match a condition
let numbers = [10, 15, 20, 25, 30];
let result = numbers.filter(function(num) {
return num >= 20;
});
console.log(result);
plaintext
Output : [20, 25, 30]
9. Array of objects
This is especially useful for your JavaScript product management practice.
let products = [
{ brand: "Samsung", price: 25000 },
{ brand: "Apple", price: 50000 },
{ brand: "Vivo", price: 18000 }
];
console.log(products[0].brand); // Samsung
console.log(products[1].price); // 50000
Each array element is an object containing product information.
Top comments (0)