Arrays vs. Objects: Fruits 🍎 and a Person πŸ‘©πŸ’»

Arrays vs. Objects: Fruits 🍎 and a Person πŸ‘©πŸ’»

Β·

4 min read

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.

JavaScript Array

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.

Objects in JavaScript (with Examples) - Scientech Easy

Object Example (Person):
Imagine an object as a person with unique characteristics (key-value pairs).
Each property describes a different aspect of the person.

Key-Value Pairs are Object Properties in JavaScript

// 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:

ArraysObjects
Ordered list (e.g., fruit basket)Unordered collection (e.g., a person)
Accessed by index ([0])Accessed by key (person.name)
Best for similar itemsBest 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

ArraysObjects
Use for, for...of, forEachUse for...in, Object.keys()
Ordered, index-based accessUnordered, key-based access
Best for lists of similar itemsBest 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! πŸš€

Β