JavaScript • Collections and Strings

Objects & Property Access — Create objects and access properties (dot vs bracket notation)

Learn how JavaScript objects store named data and how dot and bracket notation let you read and write properties.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

Historical Context & Motivation

Early programming languages stored data in simple variables and flat arrays, which worked fine for basic tasks. However, as software grew more complex, developers needed a way to group related pieces of data together under a single name — something that could hold a person's first name, last name, and age all in one place. This need gave rise to objects, one of the most important data structures in modern programming. JavaScript, which was designed in just ten days in 1995, placed objects at the very core of the language. In fact, nearly everything in JavaScript is an object, from arrays to functions.

1967 • Simula Introduces Objects

The Simula programming language in Norway introduced the concept of bundling data and behavior together, laying the groundwork for object-oriented programming.

1995 • JavaScript Is Born

Brendan Eich created JavaScript at Netscape. He built objects as a core feature, using a lightweight key-value pair syntax inspired by the Self language.

2002 • JSON Emerges

Douglas Crockford formalized JSON (JavaScript Object Notation) as a data-exchange format, proving that the object syntax was so intuitive it could serve as a universal standard.

2015 • ES6 Modernizes Objects

ECMAScript 2015 (ES6) introduced shorthand property names, computed property keys, and destructuring, making object creation and property access even more flexible.

The central question this lesson addresses is straightforward: how do you create an object in JavaScript, and once you have one, how do you read and write its properties using dot notation and bracket notation? Understanding the difference between these two approaches is essential for writing clean, bug-free code.

SECTION 2

Core Principles & Definitions

Before diving into syntax, you need to understand four foundational ideas that make JavaScript objects work. Think of these as the building blocks that every object-related feature rests on.

1

Object

An object is an unordered collection of key-value pairs. Each key (also called a property name) is a string, and its associated value can be any data type — a number, a string, a boolean, another object, or even a function.
2

Property

A property is one key-value pair inside an object. For example, name: "Alice" is a property where the key is name and the value is "Alice".
3

Dot Notation

Dot notation uses a period to access a property: obj.key. It is concise and readable, but the key must be a valid identifier (no spaces, no starting with a number, no special characters).
4

Bracket Notation

Bracket notation uses square brackets and a string: obj["key"]. It is more flexible — you can use variables, strings with spaces, or computed expressions as property names.
5

Object Literal

An object literal is the curly-brace syntax { } used to create an object directly in your code. It is the most common way to create objects in JavaScript.
✦

KEY TAKEAWAY

Think of a JavaScript object like a backpack with labeled pockets. Each pocket has a label (the key) and something stored inside (the value). Dot notation is like calling out a pocket's name — quick and easy. Bracket notation is like reading the name off a slip of paper — more flexible because the paper could say anything, including pocket names with spaces or names you don't know until runtime.

SECTION 3

Visual Explanation — Object Anatomy

JavaScript Object: studentconst student = {name:"Alice"← key: name, value: "Alice"age:16← key: age, value: 16grade:"11th"← key: grade, value: "11th"gpa:3.8← key: gpa, value: 3.8};
The diagram above shows a student object with four properties. Each row represents one key-value pair. The keys (shown in cyan) are always strings, while the values (shown in green or gold) can be any type.

Notice how the object is wrapped in curly braces { }. Inside, each property follows the pattern key: value, and properties are separated by commas. The keys in this example (name, age, grade, gpa) are all simple identifiers, which means you can use either dot notation or bracket notation to access them. When you want to retrieve Alice's GPA, you could write student.gpa or student["gpa"] — both return 3.8.

SECTION 4

How It Works — Dot vs Bracket Under the Hood

Both dot notation and bracket notation ultimately do the same thing — they look up a property name on an object and return its value. The difference lies in how the property name is provided. Understanding this distinction will help you choose the right notation in every situation.

Dot Notation

With dot notation, you type the property name directly after a period. The JavaScript engine reads the exact characters you write and searches the object for a matching key. The syntax is object.propertyName. Because the engine takes the name literally, the property name must follow the rules of a JavaScript identifier: it cannot start with a number, it cannot contain spaces, and it cannot use reserved characters like hyphens.

DOT NOTATION SYNTAX

object.propertyName→valueobject.propertyName → value

The property name is written literally. student.name always looks for the key "name".

Bracket Notation

With bracket notation, you place an expression inside square brackets. The JavaScript engine evaluates that expression first, converts the result to a string, and then uses that string to find the matching key. This means you can pass a variable, a concatenated string, or any expression — making bracket notation far more flexible.

BRACKET NOTATION SYNTAX

object[expression]→valueobject[expression] → value

The expression is evaluated at runtime. let prop = "name"; student[prop] evaluates prop to "name", then looks up that key.

Writing (Setting) Properties

Both notations also let you create or update properties. Writing student.email = "alice@school.edu" or student["email"] = "alice@school.edu" will either add a new email property or overwrite its existing value. If the property does not yet exist, JavaScript automatically creates it — no special declaration is needed.

⚠

Undefined, not an Error

If you try to access a property that does not exist on an object, JavaScript does not throw an error. Instead, it returns undefined. For example, student.phone returns undefined if no phone property has been set. This is a common source of subtle bugs, so always double-check your property names!

SECTION 5

Dot vs Bracket — When to Use Which

Now that you know the mechanics, the natural follow-up question is: when should you use dot notation and when should you reach for bracket notation? The diagram and table below lay out the decision clearly.

Decision Flowchart: Dot or Bracket?Do you know the key at write-time?YESNO (variable)Is the key a valid identifier?Use BRACKET notationYESNOUse DOT notationUse BRACKET notationDOT examples:student.name // "Alice"student.age // 16student.gpa = 3.9 // updateBRACKET examples:student["name"] // "Alice"student[prop] // variableobj["full name"] // spaces OK
This flowchart walks you through deciding which notation to use. Start at the top: if you know the exact key and it's a valid identifier, dot notation is the cleanest choice. Otherwise, reach for bracket notation.
FeatureDot NotationBracket Notation
Syntaxobj.keyobj["key"] or obj[variable]
Key with spaces?❌ Not allowed✅ Allowed: obj["first name"]
Key from a variable?❌ Not possible✅ obj[myVar]
Key starts with a number?❌ Syntax error✅ obj["2ndPlace"]
ReadabilityVery clean and shortSlightly more verbose
Common use caseKnown, simple property namesDynamic keys, computed names, or special characters

Comparison of dot and bracket notation capabilities

SECTION 6

Worked Example — Building a Movie Object

Let's walk through a complete example where we create a movie object, access its properties with both notations, and dynamically add new properties based on user input.

Creating and Accessing a Movie Object

  1. 1

    Step 1 — Create the Object Literal

    We define a movie object with three properties using the object literal syntax: const movie = { title: "Inception", year: 2010, director: "Christopher Nolan" };
    Object created with keys title, year, and director.
  2. 2

    Step 2 — Read with Dot Notation

    Since title is a valid identifier, we use dot notation for a clean read: console.log(movie.title);
    Output: "Inception"
  3. 3

    Step 3 — Read with Bracket Notation

    Bracket notation produces the same result when using a string: console.log(movie["director"]);
    Output: "Christopher Nolan"
  4. 4

    Step 4 — Use a Variable with Bracket Notation

    Suppose the user picks which property to display. We store the choice in a variable and pass it to bracket notation: let userChoice = "year"; console.log(movie[userChoice]); Here userChoice evaluates to the string "year", so the engine looks up movie["year"]. Note: movie.userChoice would NOT work here — it would look for a literal key called "userChoice", which doesn't exist.
    Output: 2010
  5. 5

    Step 5 — Add a New Property

    We can add a rating property that didn't exist when the object was created: movie.rating = 8.8; console.log(movie.rating);
    Output: 8.8 — the property was created automatically.
⚠

Common Mistake

A frequent beginner error is writing movie.userChoice when they mean movie[userChoice]. With dot notation, the engine takes the name literally — it searches for a property called "userChoice" instead of evaluating the variable. If you need a dynamic lookup, you must use brackets.

SECTION 7

Strengths & Limitations

JavaScript objects are incredibly versatile, but like any tool, they have trade-offs. The table below summarizes the key strengths and limitations of objects and property access patterns.

StrengthsLimitations
Flexible structure — properties can be added or removed at any timeNo built-in error if you access a nonexistent property (returns undefined)
Values can be any type, including nested objects and functions (methods)Property order is not guaranteed for non-integer keys in all engines
Dot notation provides clean, readable syntax for most use casesDot notation cannot handle dynamic keys, keys with spaces, or keys that start with numbers
Bracket notation handles every valid string key and supports runtime computationBracket notation is slightly more verbose and can reduce readability if overused
JSON, the universal data exchange format, is directly based on object syntaxLarge objects with many properties can become hard to manage without additional patterns like classes

Strengths and limitations of JavaScript objects and property access

✦

KEY TAKEAWAY

Use dot notation as your default because it's short and readable. Switch to bracket notation only when you need to — for dynamic keys, keys with special characters, or computed property names. Think of dot notation like calling a friend by their first name, and bracket notation like looking them up by a name tag that might change.

SECTION 8

Connection to Advanced Concepts

Once you master basic object creation and property access, you'll encounter more advanced features built on the same foundation. The table below previews how today's concepts connect to topics you'll explore later in your JavaScript journey.

What You Learned TodayWhere It Leads
Object literals { }Classes & Constructors — Create reusable blueprints for objects with class and new
Dot & bracket property accessDestructuring — Extract multiple properties at once: const { name, age } = student;
Dynamic keys via bracketsComputed property names — Use expressions as keys inside literals: { [expr]: value }
Adding properties after creationObject.freeze & Object.seal — Lock objects to prevent accidental modifications
Objects as key-value storesMap & WeakMap — Dedicated key-value collections with any type of key, better performance for frequent additions/deletions

How basic objects connect to advanced JavaScript features

Every one of these advanced features assumes you understand how objects store key-value pairs and how dot and bracket notation work. Mastering today's lesson gives you the foundation for object-oriented programming, API data handling, and virtually every real-world JavaScript application.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why student.name and student["name"] produce the same result, but student.name and student[name] (without quotes) might not. What is the critical difference?
Show answer
Both student.name and student["name"] look up the key "name" on the object, so they return the same value. However, student[name] (no quotes) treats name as a variable. The JavaScript engine evaluates the variable first, and whatever string it holds becomes the key used for the lookup. If name is undefined or holds a different string, the result will differ from student.name. The critical difference is that dot notation always uses the literal text you type, while bracket notation evaluates the expression inside the brackets.

Question 2: BASIC CALCULATION

Given the following code, what does console.log(car.year) output? const car = { make: "Toyota", model: "Camry", year: 2023 }; car.year = 2024;
Show answer
The output is 2024. The object car is created with year set to 2023. The next line uses dot notation to overwrite that property with 2024. When we then read car.year, it returns the updated value. Even though car was declared with const, const prevents reassignment of the variable, not modification of the object's properties.

Question 3: INTERMEDIATE

Write a function called getProperty that takes an object and a string representing a property name, then returns the value of that property. Which notation must you use inside the function, and why?
Show answer
You must use bracket notation because the property name comes from a parameter (a variable), not a literal name known at write-time. Here is the function: function getProperty(obj, propName) { return obj[propName]; } If you wrote return obj.propName, the engine would look for a literal key called "propName" on the object, which almost certainly doesn't exist. By using obj[propName], the engine evaluates the variable propName and uses its string value as the key. For example, getProperty({ score: 95 }, "score") returns 95.

Question 4: APPLIED

You're building a contacts app. Each contact is an object with properties like "first name", "last name", and "phone number" (note: these keys contain spaces). Write code to create a contact object and then log the contact's phone number. Can you use dot notation for these keys? Explain.
Show answer
You cannot use dot notation for keys with spaces because contact.first name would cause a syntax error — JavaScript would see contact.first as one expression and name as something unexpected. You must use bracket notation: const contact = { "first name": "Maria", "last name": "Garcia", "phone number": "555-0142" }; console.log(contact["phone number"]); // "555-0142" A best practice in JavaScript is to use camelCase keys (like firstName) so you can use dot notation. But when you receive data from external sources (like a JSON API), keys with spaces are common, and bracket notation handles them perfectly.

Question 5: CRITICAL THINKING

Consider this code: const settings = {}; const keys = ["volume", "brightness", "contrast"]; const values = [75, 50, 60]; for (let i = 0; i < keys.length; i++) { settings[keys[i]] = values[i]; } Explain step by step what happens in the loop. Why would dot notation be impossible here? What does the settings object look like when the loop finishes?
Show answer
The loop runs three times. On each iteration, keys[i] retrieves a string from the keys array and values[i] retrieves the matching number. Iteration 0: settings["volume"] = 75. Iteration 1: settings["brightness"] = 50. Iteration 2: settings["contrast"] = 60. Dot notation is impossible because the key name changes on every iteration — it comes from a variable expression (keys[i]), not a literal name known in advance. You can't write settings.keys[i] because that would look for a property literally named "keys" on settings. The final object is { volume: 75, brightness: 50, contrast: 60 }. This pattern of dynamically building objects from arrays is extremely common in real applications.

SUMMARY

Lesson Summary

Summary

A JavaScript object is an unordered collection of key-value pairs created with the object literal syntax { key: value }. Each key is a string (the property name), and each value can be any data type. Properties can be read or written at any time — JavaScript objects are dynamic and flexible.

You access properties using two notations. Dot notation (obj.key) is concise and ideal when the key is a known, valid identifier. Bracket notation (obj["key"] or obj[variable]) is essential when the key contains spaces, starts with a number, or is stored in a variable. Default to dot notation for readability, and switch to bracket notation when flexibility is needed. Mastering both unlocks every advanced JavaScript pattern from destructuring to class-based programming.

Varsity Tutors • JavaScript • Objects & Property Access — Create objects and access properties (dot vs bracket notation)