← Back to Course Overview

Module 2: Objects and Arrays

Working with Objects

Welcome to the world of Objects! JavaScript is called an object-oriented programming language, or OOP for short. This means that JavaScript organizes its software design around objects that can contain data or code. Objects are powerful because they allow us to store multiple related values together in a single container.

What are Objects?

Objects simplify storing values by grouping related values into labeled containers. For example, an inventory app for a grocery store would require variables for item names, prices, and stock quantities. Without objects, finding information for specific items becomes difficult as more variables are added. Objects solve this problem by providing a centralized container to store related values.

Object Structure

An object is an unordered collection of properties and values, called key-value pairs, separated by commas inside curly braces. Each key (property name) is linked to a value, which can be of any data type (strings, numbers, booleans, arrays, other objects, or even functions).

Declaring an Object

const person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30,
  isStudent: false
};
// property names don't need quotes if they would make valid variable names
// the values ('John', 'Doe', 30, false) can be of any type

Pro Tip

If you want a property name that contains spaces or special characters, you must wrap it in quotes. For example: 'first name' instead of firstName.

Accessing Object Properties

There are two ways to access properties from an object:

  1. Dot Notation: Using a period between the object name and property name
  2. Bracket Notation: Using square brackets with the property name as a string
// Dot notation
console.log(person.firstName); // "John"

// Bracket notation
console.log(person['lastName']); // "Doe"

Bracket notation is particularly useful when:

  • The property name contains spaces or special characters
  • The property name is stored in a variable
  • You need to access properties dynamically at runtime

Modifying Objects

Unlike primitive data types, objects in JavaScript are mutable, meaning you can change their properties after creation:

Methods for Modifying Objects

  • Setting properties: Use dot or bracket notation to set or update property values
  • Adding properties: Assign values to new property names to add them to the object
  • Deleting properties: Use the delete operator to remove properties from an object
// Updating an existing property
person.age = 31;

// Adding a new property
person.email = 'john.doe@example.com';

// Deleting a property
delete person.isStudent;

Working with Arrays

Arrays are another essential data structure in JavaScript. They allow you to store multiple values in a single variable, arranged in an ordered sequence. Unlike objects which use named properties, arrays use numbered indices to access elements.

What are Arrays?

An array is an ordered collection of values, which can be of any type (strings, numbers, objects, even other arrays). Arrays are particularly useful when you need to store a list of related items, such as a list of users, products, or tasks.

Array Characteristics

  • Ordered: Elements maintain their position in the sequence
  • Zero-indexed: The first element is at position 0, the second at position 1, etc.
  • Dynamic: Arrays can grow or shrink in size as needed
  • Heterogeneous: Arrays can contain different types of values

Declaring an Array

The most common way to create an array is using array literal syntax with square brackets:

const fruits = ['Apple', 'Banana', 'Cherry'];
const mixedArray = ['Hello', 42, true, [1, 2, 3], {name: 'John'}];

Accessing Array Elements

To access elements in an array, use square brackets with the index number of the element you want to retrieve:

const colors = ['Red', 'Green', 'Blue'];

console.log(colors[0]); // 'Red' (first element)
console.log(colors[1]); // 'Green' (second element)
console.log(colors[2]); // 'Blue' (third element)
console.log(colors[3]); // undefined (index out of bounds)

Remember

Array indices start at 0, not 1. The first element is at index 0, the second at index 1, and so on. Accessing an index that doesn't exist returns undefined.

Modifying Arrays

Arrays are mutable, meaning you can change their contents after creation:

const numbers = [10, 20, 30, 40];

// Changing an existing element
numbers[1] = 25; // [10, 25, 30, 40]

// Adding a new element to a specific position
numbers[4] = 50; // [10, 25, 30, 40, 50]

// Creating a "sparse" array by skipping indices
numbers[6] = 70; // [10, 25, 30, 40, 50, undefined, 70]

Array Length

The length property tells you how many elements are in an array:

const colors = ['Red', 'Green', 'Blue'];
console.log(colors.length); // 3

The length property is always one more than the highest index in the array. You can also set the length property to truncate an array:

const numbers = [1, 2, 3, 4, 5];
numbers.length = 3;
console.log(numbers); // [1, 2, 3] - the last two elements are removed

String to Array Conversion

The split() method allows you to convert a string into an array by splitting it at a specified delimiter:

const sentence = 'Hello, world! How are you?';

// Split by spaces
const words = sentence.split(' ');
console.log(words); // ['Hello,', 'world!', 'How', 'are', 'you?']

// Split by commas
const parts = sentence.split(',');
console.log(parts); // ['Hello', ' world! How are you?']

// Split by characters
const chars = sentence.split('');
console.log(chars); // ['H', 'e', 'l', 'l', 'o', ',', ' ', ...]

Common Use Case

The split() method is often used to parse CSV data, process text, or extract specific parts from structured strings.

Looping Over Data Structures

Working with objects and arrays often requires processing multiple values. Loops allow you to perform operations on each item in a collection, saving you from writing repetitive code.

Basic Looping Concepts

JavaScript provides several ways to loop through data structures. The most common approaches are:

Common Loop Types

  • for loops: Traditional loops with initialization, condition, and increment steps
  • while loops: Conditional loops that continue as long as a condition is true
  • for...of loops: Modern syntax for iterating over array elements
  • for...in loops: Used for iterating over object properties

Looping Over Array Indices

The classic for loop is often used to iterate through arrays using their indices:

const fruits = ['Apple', 'Banana', 'Cherry', 'Dragon fruit'];

// Looping through array indices
for (let i = 0; i < fruits.length; i++) {
  console.log(`Fruit ${i+1}: ${fruits[i]}`);
}
// Fruit 1: Apple
// Fruit 2: Banana
// Fruit 3: Cherry
// Fruit 4: Dragon fruit

Benefits of Using Indices

  • You have access to the current index position
  • You can process only certain elements by adding conditions
  • You can modify the array during iteration
  • You can iterate through only part of the array

Looping Over Object Properties

The for...in loop is designed specifically for iterating over object properties:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30,
  email: 'john.doe@example.com'
};

// Looping through object properties
for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}
// firstName: John
// lastName: Doe
// age: 30
// email: john.doe@example.com

You can also use Object.keys(), Object.values(), or Object.entries() to extract and loop through object data:

// Get all keys as an array
const keys = Object.keys(person);
console.log(keys); // ['firstName', 'lastName', 'age', 'email']

// Get all values as an array
const values = Object.values(person);
console.log(values); // ['John', 'Doe', 30, 'john.doe@example.com']

// Get all key-value pairs as arrays
const entries = Object.entries(person);
console.log(entries);
// [['firstName', 'John'], ['lastName', 'Doe'], ['age', 30], ['email', 'john.doe@example.com']]

Guided Project

In this guided project, you'll put your knowledge of objects and arrays into practice by building a small application. You'll create objects, access and modify their properties, work with arrays, and use loops to process collections of data.

Project Objectives

  • Create and manipulate JavaScript objects with various properties
  • Work with arrays of objects to represent collections of data
  • Use loops to process and transform data
  • Apply your understanding of accessing, adding, and modifying properties
  • Solve real-world problems using objects and arrays

Follow along with the video to complete the guided project. The instructor will walk you through each step and explain how objects and arrays are used in practical scenarios.

Additional Resources