COMPUTER PROGRAMMING 1 (JAVASCRIPT) • CORE DATA STRUCTURES

Objects vs. Arrays — I can choose objects vs arrays based on whether lookup is by named key or by position and justify.

Learn when to store data by named key versus by position, and why your choice matters.

Historical Context & Motivation

Long before modern programming languages existed, computer scientists struggled with a fundamental question: how should a program organize its data so it can find what it needs quickly? Early computers had extremely limited memory, so every byte counted. Programmers needed structures that could store collections of related values and retrieve them efficiently. This need gave rise to two foundational approaches—indexed collections (arrays) and key-value mappings (objects or dictionaries)—that remain at the heart of every programming language today.

1957
Fortran Introduces Arrays
IBM's Fortran language popularized the array as a way to store ordered lists of numbers, accessed by a numeric index starting at 1.
1960
LISP and Associative Lists
The LISP language introduced association lists, an early form of key-value pairs where data was looked up by name rather than by position.
1995
JavaScript Is Born
Brendan Eich created JavaScript in 10 days, building both arrays and objects into the language as first-class data structures. Objects used curly braces {} and arrays used square brackets [].
2002
JSON Emerges
Douglas Crockford formalized JSON (JavaScript Object Notation), a data format built entirely on objects and arrays, proving that these two structures could represent virtually any data.

From this history, a central question emerges: when you have a collection of data, should you reach for an array or an object? The answer depends on whether you need to look things up by their position in a sequence or by a meaningful name. Let's explore exactly how to make that decision.

Core Principles & Definitions

Before diving into code, you need to understand the core ideas that separate arrays from objects. Both are ways to group multiple values into a single variable, but they organize and retrieve those values in fundamentally different ways.

1

Array — Ordered by Position

An array is an ordered list where each element has a numeric index starting at 0. You access items by their position: myArray[2] gives you the third element.
2

Object — Labeled by Key

An object is an unordered collection of key-value pairs. You access items by a descriptive string key: student.name gives you the student's name.
3

Index vs. Key

An index is a number representing position (0, 1, 2, …). A key is a descriptive string like "email" or "score". This distinction drives your data structure choice.
4

Order Matters vs. Labels Matter

Use an array when sequence and position matter (a playlist, a ranking). Use an object when descriptive labels matter (a user profile, a config file).
✦ KEY TAKEAWAY
Think of an array like a row of numbered lockers in a hallway—you find your locker by counting from the start. An object is like a filing cabinet with labeled folders—you pull the folder marked "grades" rather than counting to the fifth drawer. If you're asking "What's in position 3?" you want an array. If you're asking "What's the student's GPA?" you want an object.

Visual Explanation

The top section shows an array where each element is accessed by a numeric index (0, 1, 2, 3). The bottom section shows an object where each value is accessed by a named key like "name" or "gpa".

Notice the critical difference in the diagram above. In the array, the only way to reach "cherry" is to know it lives at position 2. The index carries no meaning beyond order—it doesn't tell you anything about what the data represents. In the object, you ask for student.gpa and the key itself tells you what the value means. This is the fundamental tradeoff: arrays give you positional access, while objects give you semantic access (access based on meaning).

How Lookup Works Under the Hood

Understanding how JavaScript actually finds your data helps you appreciate why the choice between arrays and objects matters. While you don't need to know every detail of how the engine works internally, the high-level idea is straightforward.

Array Lookup — By Position

When you write fruits[2], JavaScript jumps directly to the memory slot at position 2. This is called random access—it doesn't have to scan through index 0 and index 1 first. The engine knows the exact offset because every position is a predictable distance from the start. Arrays also have a built-in .length property that tells you how many elements they contain, which is useful for looping.

ARRAY ACCESS SYNTAX
arrayName[index] → value at that position
The index is always a non-negative integer. JavaScript arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.

Object Lookup — By Named Key

When you write student.name or equivalently student["name"], JavaScript uses a hash map internally—a lookup table that converts the string key into a memory address. This means you can jump straight to any property without scanning the entire object. The key is always a string (or a Symbol), and it describes what the value represents.

OBJECT ACCESS SYNTAX
objectName.key or objectName["key"] → value for that key
Both dot notation (obj.key) and bracket notation (obj["key"]) retrieve the same value. Use bracket notation when the key is stored in a variable or contains spaces.
💡 Quick Decision Rule
Ask yourself: "Am I looking something up by position number or by a descriptive name?" If by position → array. If by name → object. This single question answers the majority of data-structure decisions in beginner JavaScript.

Choosing the Right Structure — A Decision Guide

Let's look at common real-world scenarios and classify which structure fits best. The diagram below walks through a decision flowchart, and the table that follows gives concrete examples you might encounter in your own projects.

Follow the flowchart from top to bottom. If the order of elements is the primary way you look things up, choose an array. If you need descriptive labels to access each value, choose an object.
Common scenarios and which data structure to choose
ScenarioBest ChoiceWhy?
A list of 20 quiz scoresArrayScores are ordered (question 1, question 2, …). You loop through them by position.
Info about a single book (title, author, pages)ObjectEach piece of data has a meaningful label. You ask for book.title, not book[0].
Names of all students in a classArrayIt's a list of similar items where you may sort, filter, or loop through them.
A phone's contact entry (name, phone, email)ObjectEach field is different. You want contact.phone rather than guessing which index the phone number is at.
High scores in a game (1st place, 2nd place, …)ArrayRanking is positional. The first element is the top score, the second element is the runner-up, etc.

Worked Example

Let's walk through a realistic scenario. You're building a small app that tracks info about a movie and a list of showtimes. We'll decide which structure to use for each piece of data and write the JavaScript.

Movie Info App — Choosing the Right Structure
1
Step 1 — Identify the DataWe need to store two things: (a) details about a movie—its title, director, year, and rating—and (b) the showtimes for that movie—10:00 AM, 1:30 PM, 4:00 PM, and 7:45 PM.
2
Step 2 — Ask the Key Question for Movie DetailsFor the movie details, will we look up data by position or by name? We want to ask "What is the movie's title?" or "What year was it released?" These are named lookups, so we choose an object.
→ Use an object for movie details.
3
Step 3 — Write the ObjectWe create the object with descriptive keys: let movie = { title: "Inception", director: "Christopher Nolan", year: 2010, rating: "PG-13" };
Access: movie.title → "Inception"
4
Step 4 — Ask the Key Question for ShowtimesFor the showtimes, will we look up by name or by position? Showtimes are an ordered sequence—first showing, second showing, etc. We might loop through all of them or ask "What is the earliest showtime?" (index 0). These are positional lookups, so we choose an array.
→ Use an array for showtimes.
5
Step 5 — Write the Array and CombineWe create the array and can even nest it inside the object: let showtimes = ["10:00 AM", "1:30 PM", "4:00 PM", "7:45 PM"]; Or, more commonly, we add it as a property of the movie object: movie.showtimes = ["10:00 AM", "1:30 PM", "4:00 PM", "7:45 PM"];
Now movie.showtimes[0] → "10:00 AM". We used an object for named attributes and an array for the ordered list.

Strengths & Limitations Comparison

Neither arrays nor objects are "better" overall—each excels at different things. The table below summarizes the key differences so you can make an informed choice every time.

Arrays vs. Objects — feature comparison
FeatureArray [ ]Object { }
Lookup styleBy numeric index (position)By named string key
Order guaranteed?Yes—insertion order is maintainedMostly—but not designed for ordering
Built-in .lengthYesNo (use Object.keys(obj).length)
Iterationfor loop, .forEach(), .map()for...in, Object.keys(), Object.entries()
Best forLists of similar items (scores, names, tasks)Entities with distinct attributes (user, car, config)
Adding items.push(), .unshift()obj.newKey = value
✦ KEY TAKEAWAY
Think of it this way: if you would naturally describe your data as "a list of ___" (a list of scores, a list of names), it's probably an array. If you'd describe it as "the ___ of a ___" (the name of a student, the price of a product), it's probably an object. This "list of" vs. "the ___ of" test works remarkably well for most beginner scenarios.

Connection to Advanced Data Structures

Once you're comfortable choosing between arrays and objects, you'll encounter more advanced structures that build on these foundations. JavaScript's Map and Set are two examples. A Map works like an object (key-value pairs) but allows any data type as a key—not just strings. A Set works like an array but guarantees every element is unique. These advanced structures solve limitations you may eventually hit with plain objects and arrays.

From beginner structures to advanced tools
Concept NowAdvanced VersionWhat It Adds
Object { }MapKeys can be any type (not just strings). Has a .size property and preserves insertion order.
Array [ ]SetAutomatically prevents duplicate values. Useful for tracking unique items.
Array of objectsDatabases (SQL, NoSQL)Stores thousands of records with powerful query capabilities for searching and filtering.

In many real projects, you'll combine arrays and objects together. For example, an online store might store an array of product objects where each object has keys like name, price, and inStock. This pattern—an array for the list, objects for each item's details—is one of the most common data shapes in JavaScript, and it's the foundation of how APIs deliver data on the modern web.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain in your own words the key difference between how you look up data in an array versus how you look up data in an object. Why does this difference matter when choosing which one to use?
PROBLEM 2 — BASIC CALCULATION
You have the following code: let pet = { species: "dog", name: "Max", age: 5 }; Write the expression to access Max's age. Then write the expression to change his age to 6.
PROBLEM 3 — INTERMEDIATE
You're building a classroom app. You need to store: (a) the teacher's name, room number, and subject; (b) a list of all student names in the class. For each piece of data, state whether you would use an array or an object, and write the JavaScript to create it.
PROBLEM 4 — APPLIED
A weather app receives the following data: city name, current temperature, humidity percentage, wind speed, and a 5-day forecast of high temperatures. Design the data structure in JavaScript. Justify each choice of array vs. object.
PROBLEM 5 — CRITICAL THINKING
A classmate stores student grades like this: let grades = ["Alice", 92, "Ben", 87, "Carlos", 95]; They argue it works fine because they can access Alice's grade at index 1. Critique this design. What problems could arise? Propose a better structure and explain why it's superior.

Lesson Summary

JavaScript gives you two core data structures for grouping values. An array stores items in an ordered sequence and lets you look them up by numeric index (position). An object stores items as key-value pairs and lets you look them up by a named key. The decision rule is simple: if the data is a list of similar items where order matters, choose an array. If the data represents a single entity with labeled attributes, choose an object.

In practice, these structures are often nested together—for example, an array of objects to represent a collection of records, or an object with array-valued properties to represent an entity that has lists within it. Mastering this choice is the foundation for organizing data throughout your programming journey, from simple scripts to full-stack web applications and JSON-based APIs.

Varsity Tutors • Computer Programming 1 (JavaScript) • Objects vs. Arrays