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.

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

SECTION 1

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.

SECTION 2

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.

SECTION 3

Visual Explanation

Array vs. Object — How Data Is StoredARRAY (ordered by index)let fruits = ["apple", "banana", "cherry", "date"];index 0"apple"index 1"banana"index 2"cherry"index 3"date"length = 4fruits[0] → "apple"OBJECT (labeled by key)let student = { name: "Ada", grade: 11, gpa: 3.8 };key: "name"value: "Ada"key: "grade"value: 11key: "gpa"value: 3.8student.name → "Ada"
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).

SECTION 4

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]→valueatthatpositionarrayName[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.keyorobjectName["key"]→valueforthatkeyobjectName.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.

SECTION 5

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.

Array or Object? — Decision FlowchartI have a collection of dataDoes order/position matter most?(Am I looking up by index 0, 1, 2…?)YESNOUSE AN ARRAY [ ]▼Do I need named labels?("name", "email", "score"…)YESUSE AN OBJECT { }Examples:• playlist of songs• leaderboard rankings• daily temperatures• list of todo itemsExamples:• user profile• game settings• product details• RGB color definition
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.
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.

Common scenarios and which data structure to choose

SECTION 6

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. 1

    Step 1 — Identify the Data

    We 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. 2

    Step 2 — Ask the Key Question for Movie Details

    For 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. 3

    Step 3 — Write the Object

    We create the object with descriptive keys: let movie = { title: "Inception", director: "Christopher Nolan", year: 2010, rating: "PG-13" };
    Access: movie.title → "Inception"
  4. 4

    Step 4 — Ask the Key Question for Showtimes

    For 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. 5

    Step 5 — Write the Array and Combine

    We 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.

SECTION 7

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.

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

Arrays vs. Objects — feature comparison

✦

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.

SECTION 8

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.

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.

From beginner structures to advanced tools

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.

SECTION 9

Practice Problems

Question 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?
Show answer
An array uses a numeric index (a position number starting at 0) to locate an element, while an object uses a named string key. This matters because if your data naturally has meaningful labels—like a person's name, age, and email—an object lets you use those labels directly (person.email), making your code more readable. If your data is a sequence of similar items where position is what matters—like a ranked list of scores—an array lets you access elements by their position (scores[0] for the first score). Choosing the right structure makes your code clearer and less error-prone.

Question 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.
Show answer
To access the age, you would write pet.age, which returns 5. To change it to 6, you would write pet.age = 6;. This works because pet is an object, so we use dot notation with the key "age" to both read and update the value. We could also use bracket notation: pet["age"] = 6;.

Question 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.
Show answer
The teacher's information has distinct, named attributes, so it should be an object: let teacher = { name: "Ms. Rivera", room: 204, subject: "Biology" };. The student names are a list of similar items where you might loop through or sort them, so it should be an array: let students = ["Alice", "Ben", "Carlos", "Diana"];. You could even combine them: teacher.students = students; to nest the array inside the object.

Question 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.
Show answer
The overall weather data for a city has distinct named fields (city, temperature, humidity, wind speed), so the top-level structure should be an object. The 5-day forecast is an ordered list of similar items (temperatures for day 1, day 2, etc.), so it should be an array. The code would be: let weather = { city: "Denver", temp: 72, humidity: 35, windSpeed: 12, forecast: [75, 78, 68, 71, 73] };. You access today's temperature with weather.temp (named key) and tomorrow's forecast with weather.forecast[1] (positional index).

Question 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.
Show answer
This design mixes names and scores in a single flat array, which is fragile and hard to maintain. To get Ben's grade, you have to know he's at index 2 and his grade is at index 3—one small insertion breaks everything. There's no clear relationship between a name and its score. A better approach is an array of objects: let grades = [{ name: "Alice", score: 92 }, { name: "Ben", score: 87 }, { name: "Carlos", score: 95 }];. Now each student's name and score are bundled together in an object (named key lookup), and the list of students is an array (positional/iterable). You can easily add or remove a student without breaking other entries, sort by score, or filter for students above 90. This pattern—an array of objects—is how professional developers model collections of records.

SUMMARY

Lesson Summary

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