Question

Add Key-Value Pairs to JavaScript Objects

javascriptobject-literal

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" or 42

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: "value2"
};

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";
Take Quiz

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:

const original = { key1: "value1", key2: "value2" };
const updated = { ...original, key3: "value3" };

console.log(updated);
// { key1: "value1", key2: "value2", key3: "value3" }

This creates a new outer object instead of changing original.

Step by Step Execution

Consider this code:

const settings = {
  theme: "light"
};

settings.fontSize = 16;

console.log(settings);

Step by step:

  1. settings is created with one property: theme: "light".
  2. JavaScript evaluates settings.fontSize.
  3. No fontSize property exists yet.
  4. The assignment operator = creates fontSize and stores 16 as its value.
  5. 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 "light" to "dark".

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;
    
Take Quiz

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) {
  return {
    ...task,
    status
  };
}

This returns a new object with all existing properties plus status. If status already exists, the later value replaces it.

Safely handle special property names

When accepting user-controlled keys, validate or restrict allowed field names. Not every arbitrary key should be copied into an application object, particularly when processing untrusted input.

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:

const obj = {};
obj.key3 = "value3";

const prevents reassignment of the variable itself, not changes to the object's properties. This is not allowed:

const obj = {};
obj = { key3: "value3" }; // TypeError

Adding properties to null or undefined

let obj;
obj.key3 = "value3"; // TypeError

Initialize the object first:

const obj = {};
obj.key3 = "value3";

Trying to change a frozen object

Object.freeze() prevents adding, changing, and removing own properties.

const obj = Object.freeze({ key1: "value1" });
obj.key3 = "value3";

Do not freeze an object if you need to add properties later.

Comparisons

ApproachExampleBest useChanges original object?
Dot notationobj.key3 = "value3"The key is a known, valid identifierYes
Bracket notationobj["key3"] = "value3"The key is a string or needs special charactersYes
Dynamic bracket notationobj[fieldName] = valueThe key comes from a variable or inputYes
Spread updateconst next = { ...obj, key3: "value3" }You need a new object rather than mutationNo

Dot notation has restrictions on property names. For example, a key containing a hyphen needs brackets:

const report = {};
report["created-at"] = "2025-01-01";

Also compare an object with a Map:

FeatureObjectMap
Typical keysStrings and symbolsValues of any type
Add entryobj[key] = valuemap.set(key, value)
Best forStructured records and JSON-like dataGeneral key-value collections with frequent entry operations
Take Quiz

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], not obj.key, when key is a variable.
  • const objects 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:

const updated = { ...obj, key3: "value3" };

Can object keys be numbers?

You can write numeric-looking keys, but ordinary object property keys are stored as strings:

const scores = {};
scores[1] = 100;
console.log(Object.keys(scores)); // ["1"]
Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more