Question
Given this JavaScript object literal:
const obj = {
key1: value1,
key2: value2
};
How can you add a new property named key3 with the value value3 to the object?
Also, how does the approach differ when the property name is known in advance versus stored in a variable?
Short Answer
You will learn that JavaScript objects can be changed after they are created. You can add a property with dot notation when its name is fixed, or bracket notation when its name is dynamic. You will also learn how object-literal values differ from string values.
Concept
A JavaScript object stores related data as properties. Each property has:
- a key (also called a property name), such as
key3 - a value, such as
"value3"or42
Objects are usually mutable, which means you can add, update, or remove their properties after creation.
const user = {
name: "Ava"
};
user.role = "admin";
console.log(user);
// { name: "Ava", role: "admin" }
The assignment user.role = "admin" creates role because it does not already exist. If role did exist, the same assignment would replace its old value.
This matters because application data often grows over time. For example, a program may add a calculated total to an order, add validation errors to a form result, or attach a request ID to an API response.
In the original object, value1, value2, and value3 are interpreted as variable names. If you mean text, write strings with quotes:
const obj = {
key1: "value1",
key2:
};
Mental Model
Think of an object as a labeled storage cabinet.
- The object is the cabinet.
- A property key is a label on a drawer.
- A property value is what you place in that drawer.
To add key3, you create a drawer labeled key3 and put "value3" inside it:
obj.key3 = "value3";
If the label is written on a piece of paper (stored in a variable), use bracket notation to read that label:
const label = "key3";
obj[label] = "value3";
Syntax and Examples
Use dot notation when you know the property name in your code.
const obj = {
key1: "value1",
key2: "value2"
};
obj.key3 = "value3";
console.log(obj);
// { key1: "value1", key2: "value2", key3: "value3" }
obj.key3 refers to the property whose literal name is key3.
Use bracket notation when the property name comes from a variable or contains characters that dot notation cannot conveniently express.
const obj = {
key1: "value1",
key2: "value2"
};
const newKey = "key3";
obj[newKey] = "value3";
console.log(obj.key3); // "value3"
Here, newKey is evaluated first, so obj[newKey] means obj["key3"].
You can also add a property while creating a new object with the spread operator:
Step by Step Execution
Consider this code:
const settings = {
theme: "light"
};
settings.fontSize = 16;
console.log(settings);
Step by step:
settingsis created with one property:theme: "light".- JavaScript evaluates
settings.fontSize. - No
fontSizeproperty exists yet. - The assignment operator
=createsfontSizeand stores16as its value. console.log(settings)prints:
{ theme: "light", fontSize: 16 }
The same syntax updates an existing property:
settings.theme = "dark";
Because theme already exists, its value changes from to .
Real World Use Cases
Adding object properties is common in many kinds of JavaScript programs:
- Form processing: add an error message for a field.
const errors = {}; errors.email = "Enter a valid email address"; - Shopping carts: calculate and add a total.
const cart = { items: 3 }; cart.total = 49.99; - API data: attach application-specific metadata.
const response = { data: [] }; response.requestId = "req_123"; - Counting data: use dynamic keys to count categories.
const counts = {}; const category = "books"; counts[category] = 1; - User preferences: save a newly selected option.
const preferences = { language: "en" }; preferences.notifications = true;
Real Codebase Usage
In real projects, property assignment is often combined with validation and clear data-flow patterns.
Add only valid values
function addNickname(profile, nickname) {
if (typeof nickname !== "string" || nickname.trim() === "") {
return;
}
profile.nickname = nickname.trim();
}
The guard clause prevents an invalid property from being added.
Build an object from dynamic input
function addField(record, fieldName, fieldValue) {
if (!fieldName) {
throw new Error("A field name is required");
}
record[fieldName] = fieldValue;
}
Bracket notation is essential because fieldName is determined at runtime.
Prefer immutable updates when needed
UI state libraries and reducer-style code often avoid changing the original object:
function updateStatus(task, status) {
{
...task,
status
};
}
Common Mistakes
Forgetting quotes around text values
This code expects variables named value1 and value2 to exist:
const obj = { key1: value1, key2: value2 };
If they are meant to be text, use strings:
const obj = { key1: "value1", key2: "value2" };
Using dot notation with a variable key
const fieldName = "key3";
obj.fieldName = "value3";
This creates a property literally named fieldName, not key3.
Use brackets for a variable key:
obj[fieldName] = "value3";
Treating a const object as completely unchangeable
This is allowed:
Comparisons
| Approach | Example | Best use | Changes original object? |
|---|---|---|---|
| Dot notation | obj.key3 = "value3" | The key is a known, valid identifier | Yes |
| Bracket notation | obj["key3"] = "value3" | The key is a string or needs special characters | Yes |
| Dynamic bracket notation | obj[fieldName] = value | The key comes from a variable or input | Yes |
| Spread update | const next = { ...obj, key3: "value3" } | You need a new object rather than mutation | No |
Dot notation has restrictions on property names. For example, a key containing a hyphen needs brackets:
Cheat Sheet
// Create an object
const obj = { key1: "value1" };
// Add or update a known key
obj.key3 = "value3";
// Add or update using a string key
obj["key3"] = "value3";
// Add or update using a variable key
const key = "key3";
obj[key] = "value3";
// Create a new object without changing the old one
const nextObj = { ...obj, key3: "value3" };
Rules:
- Assignment adds a property if it is missing and overwrites it if it exists.
- Use quotes for string values:
"value3". - Use
obj[key], notobj.key, whenkeyis a variable. constobjects can have their properties changed unless they are frozen.- Use bracket notation for keys such as
"first-name"or"2025".
FAQ
How do I add a property to a JavaScript object?
Use assignment with dot notation:
obj.key3 = "value3";
Does adding a property overwrite an existing property?
Yes. If key3 already exists, obj.key3 = "value3" replaces its previous value.
When should I use brackets instead of dot notation?
Use brackets when the property name is held in a variable or is not a standard identifier:
obj[fieldName] = value;
obj["first-name"] = "Ava";
Why does obj.key = value not use the value of the key variable?
After a dot, JavaScript uses the literal property name. obj.key always means the property named "key". Use obj[key] to evaluate the variable.
Can I add properties to an object declared with const?
Yes. You can change its properties, but you cannot assign a completely different object to that variable.
How do I add a key without changing the original object?
Create a copy with object spread:
Mini Project
Description
Build a small score tracker that stores player names as object keys and their scores as values. It demonstrates adding properties dynamically, updating existing properties, and reading the completed object.
Goal
Create a function that records scores for named players and returns the resulting score object.
Requirements
Initialize an empty object to store scores.
Add scores using player names supplied in variables.
If a player is recorded more than once, add the new points to that player's current score.
Return the final score object.
Demonstrate the function with at least three score entries.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.