An array is a list-like object used to store multiple values in a single variable. Arrays are ordered and indexed starting from 0.
const colors = ["red", "green", "blue"];
const numbers = new Array(1, 2, 3);
console.log(colors[0]); // red
colors[1] = "yellow"; // update second element
console.log(colors.length); // 3
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
for (let color of colors) {
console.log(color);
}
colors.push("purple"); // add to end
colors.pop(); // remove from end
colors.shift(); // remove from start
colors.unshift("black"); // add to start
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8]
const even = nums.filter(n => n % 2 === 0); // [2, 4]
const total = nums.reduce((sum, n) => sum + n, 0); // 10
const matrix = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(matrix[1][0]); // 3
pop()
map(), filter()
Objects are used to store data as key-value pairs. They are ideal for representing structured data like a person or product.
const person = {
name: "Ali",
age: 30,
city: "Colombo"
};
console.log(person.name); // Ali
person.age = 31;
person.country = "Sri Lanka";
delete person.city;
for (let key in person) {
console.log(key + ": " + person[key]);
}
const student = {
name: "Sara",
grades: [85, 92, 78]
};
console.log(student.grades[1]); // 92
const products = [
{ name: "Pen", price: 10 },
{ name: "Book", price: 50 }
];
console.log(products[0].name); // Pen