DEV Community

Cover image for Exploring Arrays and Objects in JavaScript
arjun
arjun

Posted on

Exploring Arrays and Objects in JavaScript

Day 6: Exploring Arrays and Objects in JavaScript

Date: December 13, 2024

Welcome to Day 6 of your JavaScript journey! Today, we delve into two essential data structures in JavaScript: Arrays and Objects. These structures form the backbone of data manipulation in modern web development. By mastering arrays and objects, you’ll unlock powerful ways to store, access, and transform data efficiently.


1. What are Arrays?

An array is a collection of items (called elements) stored at contiguous memory locations. In JavaScript, arrays are versatile and can hold mixed data types.

Creating Arrays

// Empty array
let emptyArray = [];

// Array with initial elements
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]

// Mixed data types
let mixedArray = [42, "Hello", true];
console.log(mixedArray); // Output: [42, "Hello", true]
Enter fullscreen mode Exit fullscreen mode

2. Manipulating Arrays

Adding and Removing Elements

  • push: Add elements to the end.
  • pop: Remove the last element.
  • unshift: Add elements to the beginning.
  • shift: Remove the first element.

Example:

let numbers = [1, 2, 3];
numbers.push(4); // Adds 4 to the end
console.log(numbers); // Output: [1, 2, 3, 4]

numbers.pop(); // Removes the last element
console.log(numbers); // Output: [1, 2, 3]

numbers.unshift(0); // Adds 0 to the beginning
console.log(numbers); // Output: [0, 1, 2, 3]

numbers.shift(); // Removes the first element
console.log(numbers); // Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

3. Common Array Methods

map: Transforms each element in an array.

let nums = [1, 2, 3, 4];
let squares = nums.map(num => num * num);
console.log(squares); // Output: [1, 4, 9, 16]
Enter fullscreen mode Exit fullscreen mode

filter: Filters elements based on a condition.

let ages = [12, 18, 22, 16];
let adults = ages.filter(age => age >= 18);
console.log(adults); // Output: [18, 22]
Enter fullscreen mode Exit fullscreen mode

reduce: Reduces the array to a single value.

let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 10
Enter fullscreen mode Exit fullscreen mode

4. What are Objects?

An object is a collection of properties, where each property is a key-value pair. Objects are perfect for representing real-world entities with attributes.

Creating Objects

let person = {
  name: "Arjun",
  age: 22,
  isStudent: true,
};
console.log(person.name); // Output: Arjun
console.log(person["age"]); // Output: 22
Enter fullscreen mode Exit fullscreen mode

5. Manipulating Objects

Adding and Updating Properties

let car = {
  brand: "Tesla",
};
car.model = "Model 3"; // Adding a new property
car.brand = "Ford";    // Updating a property
console.log(car); // Output: { brand: "Ford", model: "Model 3" }
Enter fullscreen mode Exit fullscreen mode

Removing Properties

delete car.model;
console.log(car); // Output: { brand: "Ford" }
Enter fullscreen mode Exit fullscreen mode

6. Common Object Methods

Iterating Over Objects

  • Object.keys: Returns an array of keys.
  • Object.values: Returns an array of values.
  • Object.entries: Returns an array of key-value pairs.

Example:

let student = { name: "Arjun", grade: "A", age: 20 };

console.log(Object.keys(student));   // Output: ["name", "grade", "age"]
console.log(Object.values(student)); // Output: ["Arjun", "A", 20]
console.log(Object.entries(student)); // Output: [["name", "Arjun"], ["grade", "A"], ["age", 20]]
Enter fullscreen mode Exit fullscreen mode

7. Arrays vs. Objects

Feature Arrays Objects
Storage Ordered collection of items. Unordered collection of key-value pairs.
Access Index-based (arr[0]). Key-based (obj.key).
Best Use Case List of related items. Grouping attributes of an entity.

8. Real-World Examples

Example 1: To-Do List Using Arrays

let tasks = ["Learn JavaScript", "Write an article", "Create a project"];
tasks.push("Read a book");
console.log(tasks); // Output: ["Learn JavaScript", "Write an article", "Create a project", "Read a book"]
Enter fullscreen mode Exit fullscreen mode

Example 2: Representing a Person Using Objects

let employee = {
  name: "Arjun",
  position: "Software Engineer",
  salary: 70000,
};
console.log(`${employee.name} is a ${employee.position}`); 
// Output: Arjun is a Software Engineer
Enter fullscreen mode Exit fullscreen mode

Example 3: Combining Arrays and Objects

let library = [
  { title: "1984", author: "George Orwell" },
  { title: "To Kill a Mockingbird", author: "Harper Lee" },
];

library.forEach(book => console.log(`${book.title} by ${book.author}`));
/*
Output:
1984 by George Orwell
To Kill a Mockingbird by Harper Lee
*/
Enter fullscreen mode Exit fullscreen mode

9. Key Takeaways

  • Arrays: Use for ordered collections; leverage methods like map, filter, and reduce for powerful transformations.
  • Objects: Use for structured data with key-value pairs; master methods like Object.keys and Object.values.
  • Combined Power: Blend arrays and objects to model and manipulate complex data.

Practice for Day 6

  1. Create an array of your favorite movies and add/remove items dynamically.
  2. Create an object to represent a book with properties like title, author, and year. Add a method to log the book details.
  3. Use map and filter on an array of numbers to get the squares of even numbers.

Next Steps

In Day 7, we’ll focus on Events and the DOM—bringing interactivity to your web applications. See you tomorrow!

Top comments (0)