| Javascript Word Counter | Javascript Array Methods | |
Arrays & Objects in JavaScript |
Arrays and Objects are the two most important data structures in JavaScript. Letβs break them down clearly with examples and a mini project.
An array is an ordered collection of values stored in a single variable. Arrays can hold numbers, strings, objects, or even other arrays.
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // apple
console.log(fruits[2]); // cherry
Property: length, fruits.length // 3
length returns the number of elements in the array (always integer β₯ 0)
Note: setting length can truncate or expand (with empty slots)
fruits.forEach(f => console.log(f));
let upper = fruits.map(f => f.toUpperCase());
let bananas = fruits.filter(f => f === 'banana');
map/filter/reduce are functional-style helpers that return new arrays/values.
let numbers = [10, 20, 30];
// Add elements
numbers.push(40); // [10,20,30,40]
// Remove last element
numbers.pop(); // [10,20,30]
// Remove first element
numbers.shift(); // [20,30]
// Add element at beginning
numbers.unshift(5); // [5,20,30]
// Loop through array
numbers.forEach(num => console.log(num));
An object is a collection of keyβvalue pairs. Keys are strings (or Symbols), and values can be any data type.
let user = {
name: "Alice",
age: 25,
isStudent: true
};
console.log(user.name); // Alice
console.log(user["age"]); // 25
user.country = "USA"; // add
user.age = 26; // update
delete user.isStudent; // delete
console.log(user);
Often, we combine arrays and objects to represent structured data.
// Array of objects
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
console.log(users[1].name); // Bob
// Object with array property
let classroom = {
teacher: "Mr. Smith",
students: ["Alice", "Bob", "Charlie"]
};
console.log(classroom.students[2]); // Charlie
const contacts = [
{ name: "Rahul", phone: "9876543210" },
{ name: "Priya", phone: "9123456780" },
{ name: "Amit", phone: "9988776655" }
];
// Add a new contact
contacts.push({ name: "Sneha", phone: "9001122334" });
// Find a contact by name
function findContact(name) {
return contacts.find(contact => contact.name === name);
}
console.log(findContact("Priya"));
// { name: "Priya", phone: "9123456780" }
| Javascript Word Counter | Javascript Array Methods | |