Table of contents
- What is a JavaScript Array?
- Key Differences:
- 1. Looping Through Arrays (Fruit Basket Example)
- a. for Loop (Classic Index-Based)
- b. for...of Loop (Simpler Value Access)
- c. forEach Method (Functional Style)
- 2. Looping Through Objects (Person Example)
- a. for...in Loop (Keys-Based)
- b. Object.keys() + forEach
- c. Object.values() (Direct Values)
- d. Object.entries() (Key-Value Pairs)
- 3. Combined Example: People and Their Favorite Fruits
- Key Differences
What is a JavaScript Array?
A JavaScript Array holds multiple values of different types as a JavaScript object. It orders elements in a list, identified by their index. Arrays in JavaScript can contain any combination of numbers, strings, objects, or even other arrays. This flexibility makes arrays a powerful tool for organizing and manipulating data.
Array Example (Fruits):
Imagine an array as a fruit basket that holds multiple similar items in order.
You can access each fruit by its position (index).
// Array = Fruit Basket
const fruitBasket = ['π', 'π', 'π', 'π₯'];
// Access by index (0-based)
console.log(fruitBasket[0]); // Output: π
// Add a new fruit
fruitBasket.push('π');
console.log(fruitBasket); // Output: ['π', 'π', 'π', 'π₯', 'π']
In the real world, everything in JavaScript is an object if it has keys and values. For example, a person is an object. He has properties like black hair, black eyes, fair skin, weight, etc., and actions like eat, sleep, walk, play, study, etc.
Object Example (Person):
Imagine an object as a person with unique characteristics (key-value pairs).
Each property describes a different aspect of the person.
// Object = Person
const person = {
name: 'Alex',
age: 28,
profession: 'Developer',
isVegetarian: true
};
// Access by property name
console.log(person.name); // Output: Alex
// Update a property
person.age = 29;
console.log(person.age); // Output: 29
Combining Them:
Objects can contain arrays, and arrays can contain objects.
// A person with a favorite fruits array
const personWithFavorites = {
name: 'Sam',
favoriteFruits: ['π', 'π₯', 'π'], // Array inside object
greet: function() {
console.log(`Hi! I love ${this.favoriteFruits.join(', ')}.`);
}
};
// Access the array inside the object
console.log(personWithFavorites.favoriteFruits[1]); // Output: π₯
// Add a new favorite fruit
personWithFavorites.favoriteFruits.push('π');
// Use the object's method
personWithFavorites.greet(); // Output: "Hi! I love π, π₯, π, π."
Key Differences:
Arrays | Objects |
Ordered list (e.g., fruit basket) | Unordered collection (e.g., a person) |
Accessed by index ([0] ) | Accessed by key (person.name ) |
Best for similar items | Best for describing entities |
1. Looping Through Arrays (Fruit Basket Example)
a. for
Loop (Classic Index-Based)
Use when you need index positions or precise control:
const fruits = ['π', 'π', 'π'];
for (let i = 0; i < fruits.length; i++) {
console.log(`Fruit ${i + 1}: ${fruits[i]}`); // Indexed access
}
// Output:
// Fruit 1: π
// Fruit 2: π
// Fruit 3: π
b. for...of
Loop (Simpler Value Access)
Use for direct access to values (no index needed):
for (const fruit of fruits) {
console.log(`Fruit: ${fruit}`);
}
// Output:
// Fruit: π
// Fruit: π
// Fruit: π
c. forEach
Method (Functional Style)
Use for side effects (e.g., logging, updating data):
fruits.forEach((fruit, index) => {
console.log(`Fruit ${index + 1}: ${fruit}`);
});
2. Looping Through Objects (Person Example)
a. for...in
Loop (Keys-Based)
Loop over keys/properties of an object:
const person = { name: 'Alex', age: 30, profession: 'Developer' };
for (const key in person) {
console.log(`${key}: ${person[key]}`); // Access value via key
}
// Output:
// name: Alex
// age: 30
// profession: Developer
b. Object.keys()
+ forEach
Convert object keys to an array and loop:
Object.keys(person).forEach((key) => {
console.log(`${key}: ${person[key]}`);
});
c. Object.values()
(Direct Values)
Loop over values only (ignoring keys):
Object.values(person).forEach((value) => {
console.log(`Value: ${value}`);
});
// Output:
// Value: Alex
// Value: 30
// Value: Developer
d. Object.entries()
(Key-Value Pairs)
Loop over key-value pairs as arrays:
Object.entries(person).forEach(([key, value]) => {
console.log(`${key} -> ${value}`);
});
3. Combined Example: People and Their Favorite Fruits
const people = [
{ name: 'Sam', favorites: ['π', 'π'] },
{ name: 'Jordan', favorites: ['π', 'π₯'] },
];
// Loop through the array of objects
for (const person of people) {
console.log(`${person.name}'s favorite fruits:`);
// Loop through the nested array
for (const fruit of person.favorites) {
console.log(`- ${fruit}`);
}
}
// Output:
// Sam's favorite fruits:
// - π
// - π
// Jordan's favorite fruits:
// - π
// - π₯
Key Differences
Arrays | Objects |
Use for , for...of , forEach | Use for...in , Object.keys() |
Ordered, index-based access | Unordered, key-based access |
Best for lists of similar items | Best for structured entities |
Conclusion π§:
Arrays store ordered lists (like fruits in a basket). Objects group key-value pairs (like a personβs traits).Use arrays to sequence items. Use objects to describe entities. Combine both to model real-world data. Code smart! π