W04 Learning Activity: JavaScript Objects
Overview
JavaScript objects are a way to group related data and functions together. Objects are a core concept in JavaScript and are used extensively in the language. In this activity, you will learn how to create and use objects in JavaScript.
"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
Instead of storing related data in complex parallel or multi-dimensional arrays, related data can be stored using 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
person
object includes propertiesname
,age
,profession
,hobbies
,address
, andisEmployed
. - It also includes a
greet
method that logs a greeting message to the console using the person's name. - The
address
property 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.true
2.
reading
(gets the first hobby in the list)3.
30
3.
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 single course, WDD 131,
add alet aCourse = { code: "WDD131", title: "Dynamic Web Fundamentals", credits: 2, };
sections
property to the object. Since the course may have more than one section, make thissections
an array of at least two (2) objects with the following properties:- section
- enrolled
- instructor
- Create a function to set the name and number of the course in HTML. Pass the course object into your function. Use dot notation to access the parts of the object that you need.
- Create another function that will output the sections into a table with an id of
sections
.
Check Your Understanding
Example Solution: CodePen ☼ – JavaScript Objects
Example: Add sections
property with two section objects
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" }
]
};
Example: Set course information to existing HTML element with and id of
courseName
function setCourseInformation(course) {
document.querySelector("#courseName").innerHTML = `${course.code} – ${course.title}`;
}
Example: Create rows in an existing HTML table with an id of sections
for each
existing section
This code separates the rendering using a map
function from the template that
builds a row.
function sectionTemplate(section) {
return `<tr>
<td>${section.sectionNumber}</td>
<td>${section.enrolled}</td>
<td>${section.instructor}</td>
</tr>`;
}
function renderSections(course) {
const html = sections.map(sectionTemplate);
document.querySelector("#sections tbody").innerHTML = html.join("");
}