JAVASCRIPT / CHAPTER 06

Objects with named properties

Beginner

Group related values in a record and pass that record to a small function.

By the end of this chapter

  • Create an object literal
  • Read and update a named property
  • Return a value derived from an object

The idea

An object groups related values under property names. In { title: "Read", done: false }, title and done are keys, and the text and boolean are their values. Curly braces create the object; a colon connects a key to a value; commas separate properties. Dot notation such as task.title reads a known property.

A property can be updated with assignment: task.done = true. This edits the existing object. A function can receive an object in a parameter and read its fields just as it reads any other input. Returning a label does not require creating a class or using inheritance. Object literals are enough for small records and are useful preparation for TypeScript object types.

A missing property normally reads as undefined. State which properties your function requires and start with objects that have that shape. Later chapters teach copying, methods, classes, and validating data from outside your program; here, concentrate on a named record and a clear returned value.

JavaScript example
const task = { title: "Read", minutes: 10 };
function describe(item) {
  return item.title + ": " + item.minutes;
}
task.minutes = 15;
console.log(describe(task));
console.log(task.title);
Result
Read: 15
Read

The function reads two properties. Changing minutes updates the number while preserving the title.

Try it yourself

Create a book object with title and pages properties. Write a function that returns its title and page count without modifying the book.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open JavaScript coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which expression reads the title property?