Computer Programming 1 (JavaScript) • Core Data Structures

Modeling with Objects — I can model a simple "record" (e.g., student, product) as an object with consistent fields.

Learn how JavaScript objects let you bundle related data into a single, organized structure.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

Before computers existed, people organized information about real-world things using paper records — think of a filing cabinet stuffed with index cards, each card holding a student's name, grade, and ID number. Every card followed the same layout so that anyone could quickly find and compare information. When programming languages came along, developers needed a way to represent these same kinds of structured records in code. The quest for a clean, flexible way to group related data together has driven some of the most important ideas in computer science.

1960s • Structs in Early Languages

Languages like COBOL and later C introduced structs — grouped fields that let programmers bundle related values (like a student's name and age) under one variable name.

1995 • JavaScript Is Born

Brendan Eich created JavaScript in just ten days. He built objects into the language from the start, making it easy to create key-value pairs without declaring a class first.

2001 • JSON Emerges

Douglas Crockford popularized JSON (JavaScript Object Notation) as a lightweight data-exchange format. JSON's syntax mirrors JavaScript objects, proving how natural the object-as-record idea had become.

2015 • ES6 Modernizes JavaScript

ECMAScript 2015 added shorthand property syntax, destructuring, and const declarations, making it even cleaner to create and work with record-style objects.

The core question this lesson addresses is: how do we take a real-world entity — a student, a product, a song — and represent it in JavaScript so the data stays organized, consistent, and easy to use? The answer is the JavaScript object, used as a record.

SECTION 2

Core Principles & Definitions

A JavaScript object is a collection of key-value pairs wrapped in curly braces. When you use an object to represent a single real-world entity with a fixed set of named fields, you are creating what programmers call a record. Each key (also called a property name) is a string that labels the data, and each value can be a string, number, boolean, array, or even another object.

1

Object Literal Syntax

Create an object by writing { key: value } inside curly braces. This is the fastest way to build a record in JavaScript.
2

Consistent Fields

A well-designed record uses the same set of property names across every similar object so your code can reliably access any field.
3

Dot & Bracket Notation

Access a value with student.name (dot) or student["name"] (bracket). Dot notation is preferred when the key is a simple identifier.
4

Mutability

Even when declared with const, you can still change the values inside an object. The const only prevents reassigning the variable itself.
✦

KEY TAKEAWAY

Think of a JavaScript object like a contact card on your phone. Every contact has the same labeled fields — Name, Phone, Email — but each card fills those fields with different information. An object-as-record works exactly the same way: the property names (keys) stay consistent, while the values change from one record to the next.

SECTION 3

Visual Explanation — Anatomy of an Object Record

Anatomy of a Student Record Objectconst student = {name:"Alice Chen",key (property name) → string valuegrade:11,key → number valuegpa:3.8,key → number value (decimal)isEnrolled:true,key → boolean valuecourses:["Math", "English"]key → array value};= Key= Value= Syntax
This diagram shows a student object with five properties. Each key (in cyan) labels the data, while each value (in amber) stores the actual information. Notice how values can be strings, numbers, booleans, or arrays.

In the diagram above, notice three important patterns. First, the entire object is wrapped in curly braces — that is how JavaScript knows you are creating an object literal. Second, each property follows the key: value pattern, separated by commas. Third, the value types are mixed: strings sit alongside numbers, a boolean, and even an array. JavaScript objects are flexible enough to hold any combination of data types, which makes them ideal for modeling real-world records where a single entity has many different kinds of attributes.

SECTION 4

How It Works — Creating, Reading, and Updating Records

Creating a Record

You create a record using an object literal. Write const product = { id: 101, name: "Notebook", price: 3.49, inStock: true }; and JavaScript allocates space in memory for an object with four properties. The const keyword means you cannot reassign product to something else, but you can still change values inside it.

Reading a Value

To read a property, use dot notation: product.name returns "Notebook". Alternatively, use bracket notation: product["name"]. Bracket notation is especially useful when the property name is stored in a variable, such as let field = "price"; console.log(product[field]);.

Updating a Value

Assign a new value to an existing key with product.price = 2.99;. You can also add a brand-new property: product.category = "School Supplies";. However, when you are modeling records, it is best practice to define all fields up front so every record of the same type has the same shape. This consistency makes your code predictable and easier to debug.

💡

Tip: Use console.log to Inspect Objects

Type console.log(product); in the browser console or Node.js to see all the keys and values inside an object at once. This is the fastest way to check that your record has the shape you expect.

SECTION 5

Keeping Records Consistent — The Shape of Data

When you have many records of the same type — say, an array of ten students — the real power of objects appears when every record has the same set of keys. Programmers call this a consistent shape (or schema). If one student object has a gpa key and another does not, your code might crash when it tries to read that missing property. Consistency prevents those hard-to-find bugs.

Array of Student Records — Consistent ShapeEvery object in the array shares the same keysconst students = [students[0]name: "Alice Chen"grade: 11gpa: 3.8isEnrolled: truecourses: ["Math", "Eng"]students[1]name: "Ben Torres"grade: 10gpa: 3.2isEnrolled: truecourses: ["Sci", "Art"]students[2]name: "Chloe Park"grade: 12gpa: 3.95isEnrolled: falsecourses: ["Hist", "CS"]Same keys↕Different values];
Three student records stored in an array. Each record is a separate object, but they all share the same five keys: name, grade, gpa, isEnrolled, and courses. Only the values differ.

When every record in your array has the same shape, you can confidently loop through the array and access any property without worrying whether it exists. For example, students.forEach(s => console.log(s.name, s.gpa)); will print every student's name and GPA, because you know those keys are present on every object. This is the foundation of data-driven programming: define the shape once, then let your code handle any number of records.

Data TypeExample Value TypeWhen to Use
string"Alice Chen"Names, descriptions, IDs that include letters
number11 or 3.8Grades, prices, quantities, scores
booleantrue or falseYes/no questions: enrolled? in stock? active?
array["Math", "English"]Lists of related items within a single record

Common value types used inside record objects

SECTION 6

Worked Example — Building a Product Catalog

Suppose you are building a small online store. You need to represent three products, each with an ID, name, price, quantity in stock, and whether the product is on sale. Let's walk through the process step by step.

Creating a Product Catalog with Consistent Records

  1. 1

    Step 1 — Decide on the Record Shape

    Before writing any code, list the fields every product needs: id (number), name (string), price (number), qty (number), and onSale (boolean). Writing this down first ensures consistency.
    Shape: { id, name, price, qty, onSale }
  2. 2

    Step 2 — Create the First Record

    Use an object literal: const p1 = { id: 1, name: "Notebook", price: 3.49, qty: 120, onSale: false };. Notice every key matches the shape we planned.
    p1.name → "Notebook"
  3. 3

    Step 3 — Create Additional Records with the Same Shape

    Build two more products: const p2 = { id: 2, name: "Pen Pack", price: 5.99, qty: 85, onSale: true }; and const p3 = { id: 3, name: "Backpack", price: 29.95, qty: 40, onSale: true };. All three share the exact same five keys.
  4. 4

    Step 4 — Store Records in an Array

    Group them: const catalog = [p1, p2, p3];. Now catalog is an array of three consistently shaped objects. You can loop through them, filter them, or sort them.
    catalog.length → 3
  5. 5

    Step 5 — Use the Data

    Find all items on sale: const saleItems = catalog.filter(p => p.onSale);. Because every record has onSale, the filter works on every element without errors.
    saleItems contains Pen Pack and Backpack
✦

KEY TAKEAWAY

The worked example follows a two-part pattern: define the shape first, then fill in the values. It is like designing a spreadsheet — you choose your column headers before typing any data into the rows.

SECTION 7

Strengths and Limitations of Object Records

StrengthsLimitations
Easy to read — keys describe the data, unlike array indicesNo built-in enforcement — JavaScript won't stop you from adding or missing a key
Flexible value types — mix strings, numbers, booleans, and arraysProperty order is not guaranteed to be meaningful (unlike arrays)
Works seamlessly with JSON for sending data to serversLarge datasets may need a database or class-based approach for better organization
Supported by powerful array methods like filter, map, and findTypos in key names fail silently — student.naem returns undefined instead of an error

Strengths vs. limitations of using plain objects as records

✦

KEY TAKEAWAY

Object-based records are like handwritten forms: they are quick and flexible but rely on the writer to follow the template. Tools like TypeScript and factory functions add "guardrails" that catch mistakes automatically, but plain objects remain the starting point for every data-modeling journey in JavaScript.

SECTION 8

Connection to Advanced Concepts

Once you are comfortable building records with plain objects, you will encounter more powerful tools that build on the same idea. Understanding where plain object records fit in the bigger picture helps you see why they are worth mastering now.

Plain Object Record (this lesson)Advanced Approach (future topics)
Shape defined manually by the programmerClasses enforce shape with a constructor
Data only — no built-in behaviorsMethods inside objects let data carry its own behaviors
No type checking in JavaScriptTypeScript interfaces validate the shape at compile time
Stored in local arraysDatabases (SQL, MongoDB) store millions of records with indexing and querying

How plain object records connect to advanced programming concepts

Every class you write in the future, every API you call, and every database you query will involve structured records. The humble plain object is where that journey begins. If you can model a student or product cleanly as a JavaScript object today, you are building the mental model you will use throughout your entire programming career.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

In your own words, explain the difference between a key and a value in a JavaScript object. Why is it important that multiple objects of the same type share the same keys?
Show answer
A key is the label or name for a piece of data (like name or grade), while a value is the actual data stored under that label (like "Alice" or 11). When multiple objects share the same keys, your code can reliably access any property without checking if it exists first. This consistency lets you loop through an array of records and process them all with the same logic, just like a spreadsheet works because every row has the same columns.

Question 2: BASIC

Write a JavaScript object literal that models a book with the following fields: title (string), author (string), pages (number), and isCheckedOut (boolean). Use any values you like.
Show answer
A correct answer would look like: const book = { title: "The Great Gatsby", author: "F. Scott Fitzgerald", pages: 180, isCheckedOut: false }; The key points are: (1) the variable is declared with const, (2) curly braces wrap the key-value pairs, (3) each key matches the required field name, and (4) each value has the correct data type — strings in quotes, numbers without quotes, and a boolean (true or false) without quotes.

Question 3: INTERMEDIATE

Given the array below, write a filter expression that returns only the products whose price is under 10 and that are inStock. const products = [ { name: "Pen", price: 1.99, inStock: true }, { name: "Tablet", price: 299.99, inStock: true }, { name: "Eraser", price: 0.75, inStock: false }, { name: "Folder", price: 3.50, inStock: true } ];
Show answer
The expression is: const result = products.filter(p => p.price < 10 && p.inStock); This checks two conditions for each object: that price is less than 10, and that inStock is true. The result array would contain the Pen ($1.99, in stock) and the Folder ($3.50, in stock). The Eraser is cheap enough but not in stock, and the Tablet is in stock but too expensive. This works reliably because every object has the same shape.

Question 4: APPLIED

You are building a gradebook app. Design a record shape for a student that includes their name, student ID, an array of test scores, and whether they have turned in their final project. Then write a function averageScore(student) that takes one student object and returns their average test score.
Show answer
First, the record shape: const student = { name: "Maria", studentId: "S2024-042", testScores: [88, 92, 76, 95], finalProjectSubmitted: true }; Then the function: function averageScore(student) { const sum = student.testScores.reduce((total, score) => total + score, 0); return sum / student.testScores.length; } Calling averageScore(student) returns 87.75. The function uses dot notation to access the testScores array, then uses reduce to sum the values and divides by the array's length. Because the record shape is consistent, this function works for any student object.

Question 5: CRITICAL THINKING

A teammate writes the following code and asks why it sometimes prints undefined instead of a number: const users = [ { name: "Ava", age: 16, email: "ava@example.com" }, { name: "Leo", age: 17 }, { name: "Mia", email: "mia@example.com", age: 15 } ]; users.forEach(u => console.log(u.email)); Identify the problem, explain why it happens, and propose a fix that prevents this bug in the future.
Show answer
The problem is that the second object (Leo) is missing the email key entirely. When JavaScript tries to read u.email on that object, it returns undefined because the property does not exist. This is the classic consequence of inconsistent record shapes. To fix it, ensure every user object has the same keys. You could either add email: "" (an empty string placeholder) to Leo's record, or write a factory function like function createUser(name, age, email = "") { return { name, age, email }; } that guarantees every object has all three keys. This pattern enforces a consistent shape and prevents silent undefined bugs.

SUMMARY

Lesson Summary

Summary

A JavaScript object lets you bundle related data into a single structure using key-value pairs. When you use objects to represent real-world entities like students or products, you are creating records. The most important best practice is maintaining a consistent shape — every record of the same type should have the same set of keys. You access values with dot notation or bracket notation, and you can update values freely even when the variable is declared with const.

Storing records in an array unlocks powerful array methods like filter, map, and forEach for processing collections of data. This approach is the foundation for more advanced patterns including classes, TypeScript interfaces, and databases. Master the plain object record now, and you will be ready for every data-modeling challenge ahead.

Varsity Tutors • Computer Programming 1 (JavaScript) • Modeling with Objects