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.

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.

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.

Visual Explanation — Anatomy of an Object Record

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.

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.

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.

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.

Common value types used inside record objects
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

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
Step 1 — Decide on the Record ShapeBefore 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
Step 2 — Create the First RecordUse 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
Step 3 — Create Additional Records with the Same ShapeBuild 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
Step 4 — Store Records in an ArrayGroup 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
Step 5 — Use the DataFind 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.

Strengths and Limitations of Object Records

Strengths vs. limitations of using plain objects as 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
✦ 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.

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.

How plain object records connect to advanced programming concepts
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

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.

Practice Problems

PROBLEM 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?
PROBLEM 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.
PROBLEM 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 } ];
PROBLEM 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.
PROBLEM 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.

Lesson 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