Part 9: All You Need to Know to Master Web Development With HTML CSS and JavaScript
Tags: webdev, javascript, programming, beginners
Published: 2023-12-28 13:00:49

## Master the Building Blocks: Objects and Arrays in JavaScript

## Contents
[Introduction](#intro)
[Objects](#obj)
[Arrays](#arrays)
[Array Methods](#methods)
[Projects](#pro)
[Bonus Tip](#bonus)


JavaScript thrives on organization, and two key structures enable <a name="intro"></a>this: Objects and Arrays. Let's dive into their power and how to use them!

![Gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/98jtki15s7ddx43xpec5.gif)

**Objects:**<a name="obj"></a>

* Imagine a box holding related data (properties) like name, age, and hobbies. That's an object!
* Properties are key-value pairs: `key: "value"`. Keys identify the data, and values are the actual information.
* You define objects using curly braces: `{}`.
* Accessing properties uses the dot notation (`object.property`) or brackets (`object["property"]`).

**Example:**

```javascript
const person = {
  name: "John Doe",
  age: 30,
  hobbies: ["reading", "hiking"],
};

console.log(person.name); // Output: "John Doe"
console.log(person["hobbies"][1]); // Output: "hiking"
```

**Objects Functions:**

- **`hasOwnProperty(propertyName)`:** Determines whether an object has a property as a direct property (not inherited).

   ```javascript
   const person = { name: "Alice", age: 30 };
   if (person.hasOwnProperty("age")) {
       console.log("Age property exists.");
   }
   ```

- **`Object.assign(target, ...sources)`:** Copies properties from one or more source objects to a target object.

   ```javascript
   const newPerson = Object.assign({}, person, { city: "New York" });
   console.log(newPerson); // Output: { name: "Alice", age: 30, city: "New York" }
   ```

- **`Object.keys(object)`:** Returns an array of all own property names (enumerable string keys) of an object.

   ```javascript
   const propertyNames = Object.keys(person);
   console.log(propertyNames); // Output: ["name", "age"]
   ```
**Arrays:**

* Think of an ordered list holding any type of data, like numbers, strings, or even other objects. That's an array!
* Elements are accessed by their index, starting from 0.
* You define arrays using square brackets: `[]`.
* Accessing elements uses the index within brackets: `array[index]`.

**Example:**

```javascript
const fruits = ["apple", "banana", "orange"];

console.log(fruits[1]); // Output: "banana"
console.log(fruits.length); // Output: 3
```
**Mutation Methods (modify the original array):** <a name="methods"></a>

- **`push(element1, ...elementN)`:** Adds one or more elements to the end of the array.
   ```javascript
   const numbers = [1, 2];
   numbers.push(3, 4);
   console.log(numbers); // [1, 2, 3, 4]
   ```
- **`pop()`:** Removes and returns the last element of the array.
   ```javascript
   const lastNumber = numbers.pop();
   console.log(numbers); // [1, 2, 3]
   console.log(lastNumber); // 4
   ```
- **`shift()`:** Removes and returns the first element of the array.
   ```javascript
   const firstNumber = numbers.shift();
   console.log(numbers); // [2, 3]
   console.log(firstNumber); // 1
   ```
- **`unshift(element1, ...elementN)`:** Adds one or more elements to the beginning of the array.
   ```javascript
   numbers.unshift(0);
   console.log(numbers); // [0, 2, 3]
   ```
- **`sort()`:** Sorts the elements of the array in place.
   ```javascript
   numbers.sort((a, b) => a - b); // Ascending order
   console.log(numbers); // [0, 2, 3]
   ```
- **`reverse()`:** Reverses the order of the elements in the array.
   ```javascript
   numbers.reverse();
   console.log(numbers); // [3, 2, 0]
   ```

**Transformation Methods (return a new array):**

- **`filter(callbackFunction)`:** Creates a new array with elements that pass a test.
   ```javascript
   const evenNumbers = numbers.filter(number => number % 2 === 0);
   console.log(evenNumbers); // [2, 0]
   ```
- **`map(callbackFunction)`:** Creates a new array by applying a function to each element.
   ```javascript
   const doubledNumbers = numbers.map(number => number * 2);
   console.log(doubledNumbers); // [6, 4, 0]
   ```
- **`reduce(callbackFunction, initialValue)`:** Reduces the array to a single value.
   ```javascript
   const sum = numbers.reduce((accumulator, number) => accumulator + number, 0);
   console.log(sum); // 5
   ```
- **`find(callbackFunction)`:** Returns the value of the first element that satisfies a test.
   ```javascript
   const firstEven = numbers.find(number => number % 2 === 0);
   console.log(firstEven); // 2
   ```
- **`findIndex(callbackFunction)`:** Returns the index of the first element that satisfies a test.
   ```javascript
   const evenIndex = numbers.findIndex(number => number % 2 === 0);
   console.log(evenIndex); // 1
   ```
- **`some(callbackFunction)`:** Tests whether at least one element satisfies a test.
   ```javascript
   const hasEven = numbers.some(number => number % 2 === 0);
   console.log(hasEven); // true
   ```
- **`every(callbackFunction)`:** Tests whether all elements satisfy a test.
   ```javascript
   const allEven = numbers.every(number => number % 2 === 0);
   console.log(allEven); // false
   ```
- **`join(separator)`:** Joins all elements of an array into a string.
   ```javascript
   const joinedString = numbers.join(", ");
   console.log(joinedString); // "2, 3, 0"
   ```
## Projects <a name="pro"></a>
**Project 1: Library Management System**

```javascript
// Create a book object with properties and methods
function Book(title, author, genre) {
  this.title = title;
  this.author = author;
  this.genre = genre;
  this.isAvailable = true;

  this.borrowBook = function() {
    if (this.isAvailable) {
      this.isAvailable = false;
      console.log(`You've borrowed ${this.title}!`);
    } else {
      console.log(`Sorry, ${this.title} is currently unavailable.`);
    }
  };

  this.returnBook = function() {
    this.isAvailable = true;
    console.log(`You've returned ${this.title}.`);
  };
}

// Create an array to store books
const library = [];
library.push(new Book("The Lord of the Rings", "J.R.R. Tolkien", "Fantasy"));
library.push(new Book("Pride and Prejudice", "Jane Austen", "Romance"));
library.push(new Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", "Sci-Fi"));

// Use array methods to manage books
console.log("Available books:");
library.filter(book => book.isAvailable).forEach(book => console.log(book.title));

// Example usage:
const borrowedBook = library[1].borrowBook(); // Borrow a book
library.unshift(new Book("Harry Potter and the Sorcerer's Stone", "J.K. Rowling", "Fantasy")); // Add a book
library.sort((a, b) => a.title.localeCompare(b.title)); // Sort books alphabetically
```

**Project 2: Shopping Cart**

```javascript
// Create a product object with properties and methods
function Product(name, price, quantity) {
  this.name = name;
  this.price = price;
  this.quantity = quantity;

  this.addToCart = function() {
    this.quantity++;
    console.log(`${this.name} added to cart.`);
  };

  this.removeFromCart = function() {
    if (this.quantity > 0) {
      this.quantity--;
      console.log(`${this.name} removed from cart.`);
    } else {
      console.log(`${this.name} is not in the cart.`);
    }
  };

  this.calculateTotal = function() {
    return this.price * this.quantity;
  };
}

// Create an array to store products
const products = [];
products.push(new Product("Apple", 1.50, 0));
products.push(new Product("Banana", 0.75, 0));
products.push(new Product("Orange", 1.25, 0));

// Use array methods to manage products and cart
let cart = [];
products[0].addToCart(); // Add an apple to the cart
cart.push(products[1]); // Add a banana to the cart

console.log("Cart items:");
cart.forEach(product => console.log(product.name, product.quantity));

console.log("Total price:", cart.reduce((total, product) => total + product.calculateTotal(), 0));
```

**Project 3: Data Analysis**

```javascript
// Create an array of scores
const scores = [85, 92, 78, 95, 81];

// Use array methods to analyze the data
console.log("Average score:", scores.reduce((sum, score) => sum + score, 0) / scores.length);
console.log("Highest score:", Math.max(...scores));
console.log("Lowest score:", Math.min(...scores));
console.log("Sorted scores:", scores.sort((a, b) => a - b)); // Sort ascending
console.log("Filtered scores above 90:", scores.filter(score => score > 90));
```

**Bonus Tip:**<a name="bonus"></a> Check out MDN Web Docs for comprehensive references on objects and arrays:

* Objects: [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* Arrays: [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)