Computer Programming 1 (JavaScript) • Core Data Structures

Object Basics — I can create objects and use dot/bracket notation to read and update properties.

Learn how JavaScript objects bundle related data together and how to access it with dot and bracket notation.

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

SECTION 1

Historical Context & Motivation

Before programming languages had sophisticated data structures, developers stored information in individual variables. Imagine tracking a student's name, age, and grade in three separate variables — now imagine doing that for hundreds of students. The code becomes messy and error-prone very quickly. The idea of bundling related data together under a single name arose out of this practical need, and it became one of the most important ideas in all of computer science: the object.

1967 • Simula Introduces Objects

Norwegian computer scientists Ole-Johan Dahl and Kristen Nygaard create Simula, the first language with object-like data grouping, designed to model real-world simulations.

1972 • Smalltalk Popularizes OOP

Alan Kay's Smalltalk language coins the term "object-oriented programming" and proves that structuring programs around objects makes code easier to understand and reuse.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript in just ten days at Netscape. He builds objects directly into the language, making them one of the core building blocks of every JavaScript program.

2015 • ES6 Modernizes Objects

ECMAScript 2015 (ES6) adds shorthand property syntax, computed property names, and destructuring, making objects even more convenient and expressive.

At its core, the concept of an object solves a simple but critical problem: how do we keep related pieces of data together so our programs stay organized? In JavaScript, objects are everywhere — the browser window, form inputs, even error messages are all objects. Understanding how to create them and access their data is the foundation of nearly everything you will build.

SECTION 2

Core Principles & Definitions

A JavaScript object is an unordered collection of key-value pairs. Each key (also called a property name) is a string that labels a piece of data, and each value is the data itself. You create an object using curly braces { }, which is called an object literal. Once you have an object, you can read, update, or add properties using either dot notation or bracket notation.

1

Object Literal

The simplest way to create an object: wrap key-value pairs inside curly braces. Example: let pet = { name: "Max", age: 3 };
2

Property (Key-Value Pair)

Each entry in an object. The key is the label (like "name"), and the value is the data (like "Max"). Keys are always strings; values can be any data type.
3

Dot Notation

Access a property by writing the object name, a period, then the key: pet.name. Clean and easy to read, but the key must be a valid identifier (no spaces or special characters).
4

Bracket Notation

Access a property by placing the key as a string inside square brackets: pet["name"]. More flexible — you can use variables and keys with spaces or special characters.
5

Dynamic Access

When the property name is stored in a variable, you must use bracket notation. Example: let key = "age"; pet[key]; returns 3.
✦

KEY TAKEAWAY

Think of an object like a contact card on your phone. The card itself is the object. Each field — name, phone number, email — is a property. The field label is the key, and the information you typed in is the value. Dot notation is like tapping directly on the "Name" label; bracket notation is like typing the label's text into a search bar. Both get you to the same data, but the search bar (brackets) lets you use a variable to choose which field to look up.

SECTION 3

Visual Explanation — Anatomy of an Object

Anatomy of a JavaScript Objectlet student = {name:"Alice",grade:10,gpa:3.8};KEY (property)VALUE (data)always a stringany data typeTwo Ways to Access PropertiesDOT NOTATIONstudent.name→ "Alice"student.grade = 11;→ updates grade to 11BRACKET NOTATIONstudent["name"]→ "Alice"let k = "gpa";student[k] → 3.8
The top panel shows the structure of an object literal with labeled keys (in cyan) and values (in green/amber). The bottom two panels contrast dot notation (left) with bracket notation (right). Notice how bracket notation can use a variable to dynamically choose which property to access.

As the diagram shows, both notations reach the same data inside the object. The key difference is flexibility. Dot notation is shorter and more readable, so it is the default choice when you know the exact property name and that name follows normal variable-naming rules (no spaces, doesn't start with a number). Bracket notation is essential when the key is stored in a variable, or when the key contains spaces, hyphens, or other special characters. Both notations work for reading a property's value and for updating or adding new properties.

SECTION 4

How It Works — Creating, Reading, Updating, and Adding

Creating an Object

You create an object by assigning an object literal to a variable. Inside the curly braces, you list properties separated by commas. Each property follows the pattern key: value. An empty object is simply let obj = {};. Values can be strings, numbers, booleans, arrays, or even other objects — any JavaScript data type is valid.

OBJECT LITERAL SYNTAX

letvariableName=key1:value1,key2:value2,...;let variableName = { key₁: value₁, key₂: value₂, ... };

Each key is a string (quotes optional if it's a valid identifier). Each value can be any data type.

Reading a Property

DOT NOTATION — READ

objectName.propertyKey→returnsthevalueobjectName.propertyKey → returns the value

Example: student.name returns "Alice". If the property doesn't exist, JavaScript returns undefined.

BRACKET NOTATION — READ

objectName["propertyKey"]→returnsthevalueobjectName["propertyKey"] → returns the value

Example: student["grade"] returns 10. You can also pass a variable: let prop = "grade"; student[prop];

Updating & Adding Properties

Updating and adding properties use the exact same syntax — an assignment with =. If the property already exists, its value is replaced. If it doesn't exist, JavaScript creates it automatically. For example, student.gpa = 4.0; updates the existing gpa property, while student.email = "alice@school.edu"; creates a brand-new property called email. This works the same way with bracket notation: student["email"] = "alice@school.edu";.

💡

When must you use bracket notation?

Use brackets when the key is stored in a variable, when the key has spaces (e.g., "first name"), when the key starts with a number, or when the key contains special characters like hyphens. In all other cases, dot notation is preferred because it is more concise.

SECTION 5

Dot vs. Bracket — A Detailed Comparison

Choosing Dot vs. Bracket Notation — Decision FlowchartDo you know the exact key name?YESNO (it's in a variable)Use BRACKET notationobj[variableName]Does the key have spaces / specials?YESNOUse BRACKET notationobj["first name"]Use DOT notation ✓obj.firstNameQuick Reference ExamplesDOT ✓car.colorcar.year = 2024;car.modelBRACKET ✓car["color"]car[prop]car["top speed"]ERRORS ✗car.top speedcar.prop(looks for literal key "prop")
This flowchart guides you through the decision of when to use dot notation versus bracket notation. The bottom row shows correct usage alongside a common mistake: writing car.prop when you mean car[prop] — dot notation looks for a literal key called "prop" instead of using the variable's value.
FeatureDot NotationBracket Notation
Syntaxobj.keyobj["key"]
Key with spaces❌ Not allowed✅ Works
Key from a variable❌ Looks for literal key✅ Evaluates the variable
ReadabilityCleaner and shorterSlightly more verbose
When to useDefault choice for simple keysDynamic access or special-character keys

Dot vs. Bracket notation comparison

SECTION 6

Worked Example — Building a Game Character

Let's walk through a complete example. Imagine you're building a simple video game and need to represent a character with several attributes. We'll create the object, read properties, update them, and add new ones.

Creating and Manipulating a Game Character Object

  1. 1

    Step 1 — Create the Object

    We define a character with three starting properties: a name, a health value, and a level number. We use an object literal.
    let hero = { name: "Kai", health: 100, level: 1 };
  2. 2

    Step 2 — Read a Property (Dot Notation)

    To display the character's name in the game UI, we read the name property using dot notation.
    console.log(hero.name); // Output: "Kai"
  3. 3

    Step 3 — Update a Property (Dot Notation)

    The character takes damage in battle. We subtract 25 from health using dot notation and the assignment operator.
    hero.health = hero.health - 25; // hero.health is now 75
  4. 4

    Step 4 — Add a New Property (Dot Notation)

    The character picks up a weapon. Since weapon didn't exist before, JavaScript creates it automatically.
    hero.weapon = "fire sword"; // { name: "Kai", health: 75, level: 1, weapon: "fire sword" }
  5. 5

    Step 5 — Read Using Bracket Notation with a Variable

    Suppose the player can choose which stat to view. We store the chosen stat in a variable and use bracket notation to look it up dynamically.
    let stat = "health"; console.log(hero[stat]); // Output: 75
  6. 6

    Step 6 — Add a Property with Special Characters (Bracket Notation)

    We want to track the character's "power level" — but since the key has a space, dot notation won't work. Bracket notation handles it.
    hero["power level"] = 42; console.log(hero["power level"]); // Output: 42
⚠

Common Mistake Alert

If you write hero.stat instead of hero[stat], JavaScript looks for a property literally called "stat" — not the value stored in the variable stat. This is one of the most common bugs beginners encounter. Remember: when the key is in a variable, always use brackets.

SECTION 7

Strengths and Limitations of Objects

StrengthsLimitations
Group related data under one variable, keeping code organized and readable.Properties are unordered — you cannot guarantee which key comes first when looping.
Dynamic — you can add, update, and delete properties at any time.No built-in duplicate-key protection; the last value assigned to a key wins silently.
Values can be any data type, including arrays and other objects (nesting).Not ideal for ordered collections of similar items — arrays are better for lists.
Bracket notation allows computed and dynamic property access.Deeply nested objects can become hard to read and debug without good naming.

Strengths and limitations of JavaScript objects

✦

KEY TAKEAWAY

Objects are like labeled filing cabinets — perfect when each drawer (property) has a unique label and you need to find things by name. If you need to find things by position (first, second, third…), reach for an array instead. Knowing which data structure to use is just as important as knowing how to use it.

SECTION 8

Connection to Advanced Concepts

The object basics you've learned here are the foundation for more powerful features in JavaScript. As you advance, you'll encounter methods (functions stored as property values), JSON (JavaScript Object Notation, the universal data format of the web), and classes (blueprints for creating many objects with the same structure). Each of these builds directly on what you know now.

What You Know NowWhat's Coming Next
Creating objects with key-value pairsAdding methods (functions as values) to objects
Dot and bracket notation for reading/writingDestructuring — extracting multiple properties at once
One object at a timeClasses and constructors — making many objects from a template
Objects in your codeJSON — sending objects between a browser and a server

From object basics to advanced concepts

Every web API you'll ever use — from fetching weather data to building interactive games — sends and receives data as objects. Mastering the basics now means you'll be ready to handle real-world data the moment you encounter it.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words: what is the difference between a key and a value in a JavaScript object? Give one real-world analogy that is different from the contact-card analogy used in this lesson.
Show answer
A key is a label or identifier for a piece of data, while the value is the actual data itself. For example, think of a dictionary: the word you look up is the key, and the definition is the value. In a JavaScript object like { color: "blue" }, color is the key (the label) and "blue" is the value (the data). Just like a dictionary can have many words, an object can have many key-value pairs.

Question 2: BASIC CALCULATION

Given the following object, what does each expression evaluate to? let book = { title: "Dune", pages: 412, genre: "sci-fi" }; a) book.title b) book["pages"] c) book.author
Show answer
a) "Dune" — dot notation reads the title property. b) 412 — bracket notation with the string "pages" returns the number of pages. c) undefined — the property author does not exist in the object, so JavaScript returns undefined rather than throwing an error.

Question 3: INTERMEDIATE

Write JavaScript code that does the following: (1) creates an object called playlist with properties name set to "Study Beats" and songCount set to 15; (2) updates songCount to 16; (3) adds a new property "is public" set to true. Explain which notation you use for step 3 and why.
Show answer
let playlist = { name: "Study Beats", songCount: 15 }; playlist.songCount = 16; playlist["is public"] = true; For step 3, bracket notation is required because the key "is public" contains a space. Dot notation (playlist.is public) would cause a syntax error because JavaScript interprets the space as the end of the property name.

Question 4: APPLIED

You are building a weather dashboard. You have this object: let weather = { city: "Denver", tempF: 58, condition: "cloudy" }; A user clicks a button labeled with the text "tempF". That button text is stored in a variable: let clicked = "tempF"; Write code to display the value of whichever property the user clicked. Then explain why weather.clicked would NOT work here.
Show answer
The correct code is: console.log(weather[clicked]); // Output: 58 You must use bracket notation because clicked is a variable whose value is the string "tempF". Writing weather.clicked would tell JavaScript to look for a property literally named "clicked" on the weather object — which doesn't exist, so it would return undefined. Bracket notation evaluates the variable first and then uses its value ("tempF") as the key.

Question 5: CRITICAL THINKING

Consider this code: let settings = {}; let keys = ["volume", "brightness", "fontSize"]; let values = [75, 80, 14]; for (let i = 0; i < keys.length; i++) { settings[keys[i]] = values[i]; } What does the settings object look like after the loop finishes? Could you replace the bracket notation with dot notation inside the loop? Explain your reasoning.
Show answer
After the loop, settings equals { volume: 75, brightness: 80, fontSize: 14 }. Each iteration takes a key from the keys array and a corresponding value from the values array, then assigns it to the object. You could NOT use dot notation here (e.g., settings.keys[i]) because dot notation requires a literal property name written directly in the code. Since the property name comes from a variable (keys[i]), only bracket notation can evaluate that expression to get the actual key string. This is a perfect example of why bracket notation exists — it enables dynamic, programmatic property access.

SUMMARY

Lesson Summary

Summary

A JavaScript object is a collection of key-value pairs created with an object literal using curly braces { }. Each key is a string label, and each value can be any data type. You read, update, and add properties with dot notation (obj.key) for simple, known keys, or bracket notation (obj["key"] or obj[variable]) when the key has spaces, special characters, or is stored in a variable.

Objects solve the problem of keeping related data organized under a single name. They are everywhere in JavaScript — from browser APIs to web data formats like JSON. Mastering object creation and both access notations gives you a solid foundation for methods, classes, and every advanced data structure you'll encounter next.

Varsity Tutors • Computer Programming 1 (JavaScript) • Object Basics — I can create objects and use dot/bracket notation to read and update properties.