Arrays and Objects

JavaScriptJavaScriptBeginner
Practice Now

Introduction

In this Lab, we continue to follow Alex on their journey as a web developer at a tech startup. The scene unfolds in the development team's workspace, where Alex is tasked with enhancing the personal finance tracker by incorporating the ability to handle multiple financial records. This crucial feature requires Alex to delve into JavaScript's arrays and objects, storing each financial record as an object within an array. The goal is to create a dynamic and interactive application that not only tracks but also organizes users' financial data efficiently. Through this endeavor, Alex aims to provide users with a clear overview of their financial activities, thus making the app more useful and engaging.

In this lab we need to store accounting records by manipulating arrays and objects. The focus is on understanding how to use arrays to store objects and how to add new elements to an array.

Knowledge Points:

  • Array manipulation (creating, traversing, adding elements)
  • Objects (creating objects, accessing and setting properties)

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/DOMManipulationGroup(["`DOM Manipulation`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/functions("`Functions`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/closures("`Closures`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") javascript/DOMManipulationGroup -.-> javascript/dom_select("`DOM Selection`") javascript/DOMManipulationGroup -.-> javascript/dom_manip("`DOM Manipulation`") javascript/DOMManipulationGroup -.-> javascript/event_handle("`Event Handling`") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("`Debugging`") javascript/ToolsandEnvironmentGroup -.-> javascript/bom("`Browser Object Model`") subgraph Lab Skills javascript/variables -.-> lab-290728{{"`Arrays and Objects`"}} javascript/data_types -.-> lab-290728{{"`Arrays and Objects`"}} javascript/arith_ops -.-> lab-290728{{"`Arrays and Objects`"}} javascript/comp_ops -.-> lab-290728{{"`Arrays and Objects`"}} javascript/loops -.-> lab-290728{{"`Arrays and Objects`"}} javascript/functions -.-> lab-290728{{"`Arrays and Objects`"}} javascript/array_methods -.-> lab-290728{{"`Arrays and Objects`"}} javascript/closures -.-> lab-290728{{"`Arrays and Objects`"}} javascript/template_lit -.-> lab-290728{{"`Arrays and Objects`"}} javascript/dom_select -.-> lab-290728{{"`Arrays and Objects`"}} javascript/dom_manip -.-> lab-290728{{"`Arrays and Objects`"}} javascript/event_handle -.-> lab-290728{{"`Arrays and Objects`"}} javascript/debugging -.-> lab-290728{{"`Arrays and Objects`"}} javascript/bom -.-> lab-290728{{"`Arrays and Objects`"}} end

Functions

Function

A function in JavaScript is a block of code designed to perform a task or calculate values. Functions are defined using the function keyword:

function greet(name) {
  return "Hello, " + name + "!";
}
console.log(greet("Alice")); // output: "Hello, Alice!"

Here, the greet function takes a parameter name and returns a greeting.

Arrow Function

Arrow functions, introduced in ES6, provide a more concise way to write functions. They are particularly useful for anonymous function expressions:

const greet = (name) => "Hello, " + name + "!";
console.log(greet("Bob")); // output: "Hello, Bob!"

Arrow functions automatically bind the this value of the current context, which is useful for callback functions and method chaining.

Array Operations

An array in JavaScript is an object used to store multiple values.

Creating an Array
let fruits = ["Apple", "Orange", "Cherry"];

JavaScript arrays are zero-indexed: the first element of an array is at index 0, the second is at index 1, and so on — and the last element is at the value of the array's length property minus 1.

Each index corresponds to a unique array element.

So how do we read the elements of the array?

Traversing an Array

Use the forEach method to traverse an array.

The forEach method takes a callback function that takes two parameters: value and index.

For example, to log each element of the fruits array:

fruits.forEach(function (value, index) {
  console.log(index, value);
});
Adding Elements

Use the push method to add an element to the end of an array.

For example, let's add a grape to the fruits array.

fruits.push("Grape");
console.log(fruits);

Objects

Objects are fundamental building blocks in JavaScript, used to store key-value pairs.

Creating an Object
let person = {
  name: "Alice",
  age: 30
};
Accessing and Setting Properties

You can access object properties using dot (.) or bracket ([]) notation:

console.log(person.name); // Using dot notation

person["age"] = 31; // Using bracket notation to set a property
console.log(person.age);

Understanding the basic usage of arrays and objects, let's start refining the code of the project.

Creating and Storing Financial Records

In this step, you'll work alongside Alex to create a structure for storing financial records as objects in an array. This setup will form the backbone of the finance tracker's data management system, allowing for dynamic updates and manipulation of financial records.

First, let's define what a financial record looks like. Each record will have a description, amount, and type (income or expense). Open your script.js and start by creating an array to hold these records:

let records = [];

Next, create a function to add new records to this array. Each record will be an object:

const addRecord = (description, amount, type) => {
  records.push({ description, amount, type });
};

You can't see anything on the page yet, because we haven't finished the function that listens for submit.

Define form.addEventListener("submit", (e) => {}) in script.js to listen for interactions when the Add button is clicked.

// Event listener for form submission to add a new record
form.addEventListener("submit", (e) => {
  e.preventDefault();
  const description = document.getElementById("description").value;
  const amount = document.getElementById("amount").value;
  const type = document.getElementById("type").value;
  addRecord(description, amount, type);
});
  • The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
  • The value property of the HTMLDataElement interface returns a string reflecting the value HTML attribute.

At this point, if you add in the addRecord function, add
console.log(records);, you can see that the data added to the record will be logged into records.

If we want to display the records added to the ledger, we need to create the renderRecords function, but before we do that we need to learn about the template string.

Template String

Template strings are defined using backticks (`) and can contain placeholders in the form of ${expression}, where expression can be any valid JavaScript expression.

let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!
Variable Interpolation

Template strings conveniently embed variable values into the string, simplifying the construction of dynamic string information.

let age = 25;
let message = `She is ${age} years old.`;
console.log(message); // Output: She is 25 years old.
Handling Multi-line Strings

In traditional JavaScript, handling multi-line strings often requires using backslashes or string concatenation. Template strings offer a more concise way to handle multi-line text.

let poem = `Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.`;
console.log(poem);

Displaying Financial Records

Now that Alex has set up a way to store financial records, the next step is to display these records dynamically on the webpage. You'll learn how to iterate over the array of financial records and display each one as part of the finance tracker's UI.

Then, in script.js, create a function to render these records:

const renderRecords = () => {
  recordsList.innerHTML = "";
  records.forEach((record, index) => {
    const recordElement = document.createElement("div");
    recordElement.classList.add("record-item");
    recordElement.innerHTML = `
                ${record.description} - ${record.amount} (${record.type}) <button onclick="deleteRecord(${index})">Delete</button>
            `;
    recordsList.appendChild(recordElement);
  });
};

After adding your test records, call renderRecords to see them displayed on the page:

renderRecords();

This function iterates over the financialRecords array, creating a new paragraph for each record and appending it to the designated container on the webpage.

Summary

In this lab, you followed Alex in taking significant strides towards making the personal finance tracker a robust application. By learning to use arrays and objects, you've enabled the app to store and display multiple financial records dynamically. This not only enhances the app's functionality but also introduces you to managing complex data structures in JavaScript, a critical skill in web development.

Through this hands-on experience, you've seen how arrays and objects can work together to organize and manipulate data in a meaningful way. This foundational knowledge sets the stage for further enhancements, such as adding interactivity and data persistence, in the development journey ahead.

Other JavaScript Tutorials you may like