W04 Learning Activity: JavaScript Objects
Overview
JavaScript objects group related data and functions together. They are a core concept in JavaScript and used extensively throughout the language. In this activity, you will learn how to create and use objects effectively.
"An object is a collection of related data and/or functionality. These usually consist of several variables and functions (which are called properties and methods when they are inside objects)." – MDN
Course Learning Outcomes
- Demonstrate proficiency with JavaScript language syntax.
- Use JavaScript to respond to events and dynamically modify HTML.
Prepare
Rather than storing related data in complex parallel or multi-dimensional arrays, you can use objects, which are more readable, stable, and maintainable.
- The JavaScript object structure is similar to a Dictionary in Python. Objects in JavaScript are collections of key:value pairs.
- The key is on the left side of the colon and the value is on the right.
- The key is a string but does not always need to be quoted. Quotes are necessary if the key has a space in it.
- The value can be anything that can be assigned to a variable in JavaScript: primitives, arrays, other objects, functions, etc.
- Keys that store data are called properties, keys that store functions are called methods.
This is an example of a JavaScript object literal (a collection of key-value pairs) representing a person in a concise and readable format.
let person = {
name: "Antonia Francesca",
age: 30,
profession: "Software Engineer",
hobbies: ["reading", "playing guitar", "hiking"],
address: {
street: "123 Camino Real",
city: "Santa Rosa",
country: "Honduras"
},
isEmployed: true,
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
- The
personobject includes propertiesname,age,profession,hobbies,address, andisEmployed. - It also includes a
greetmethod that logs a greeting message to the console using the person's name. - The
addressproperty is an object itself, containing nested properties:street,city, andcountry. - You can access and modify the properties and invoke the methods of the person object using bracket [] or dot notation.
✓ Determine the output of the following statements given the person object defined above.
-
console.log(person['isEmployed']); // bracket notation -
console.log(person.hobbies[0]); // dot notation -
console.log(person.age); // dot notation -
console.log(person['address'].city); // combined notation
Answers
1.true2.
reading (returns the first hobby in the list)3.
304.
Santa Rosa
Updating a value works like you expect.
person.age = 31;
Reference: Object Basics – MDN
Activity Instructions
Use objects and encapsulation to create a representation of a typical college course schedule.
The following CodePen ☼ JavaScript Objects can be used to work on this activity.
- Given the following object literal for a course,
add alet aCourse = { code: "WDD131", title: "Dynamic Web Fundamentals", credits: 2, };sectionsproperty to the object. Since the course may have more than one section, make thissectionsan array of at least two (2) items with the following properties:- section
- enrolled
- instructor
Check Your Understanding
let aCourse = { code: "WDD131", title: "Dynamic Web Fundamentals", credits: 2, sections : [ { section: "001", enrolled: 95, instructor: "Roberto Diaz Rodriguez" }, { section: "002", enrolled: 80, instructor: "Sarah Gobble" } ] }; - Create a function named
setCourseInformation()to display the course code and title in HTML. Pass the course object as a parameter. Use dot notation to access the properties you need and update the element with idcourseName.Check Your Understanding
function setCourseInformation(course) { document.querySelector("#courseName").innerHTML = `${course.code} – ${course.title}`; } - Create a function named
renderSections()that displays the course sections as rows in a table with idsections.Check Your Understanding
function renderSections(course) { const tbody = document.querySelector("#sections tbody"); let rows = ""; for (const section of course.sections) { rows += `<tr> <td>${section.section}</td> <td>${section.enrolled}</td> <td>${section.instructor}</td> </tr>`; } tbody.innerHTML = rows; }
Example Solution: CodePen ☼ JavaScript Objects