How can I add a key/value pair to a JavaScript object?
Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add field key3 with value3 to the object?
To add a key-value pair to a JavaScript object, you can use either dot notation (obj.key3 = value3) or bracket notation (obj['key3'] = value3). Both methods achieve the same result, but they are used in different scenarios based on your specific needs.
Contents
- Dot Notation Method
- Bracket Notation Method
- When to Use Each Method
- Advanced Examples with Dynamic Keys
- Common Mistakes to Avoid
- Performance Considerations
Dot Notation Method
The dot notation is the most straightforward and commonly used method for adding key-value pairs to JavaScript objects. Here’s how you would add key3 with value3 to your object:
var obj = {key1: 'value1', key2: 'value2'};
obj.key3 = 'value3';
This approach is clean and readable, making it ideal for when you know the exact key name in advance. The dot notation requires that the key be a valid JavaScript identifier (no spaces, no special characters except underscore and dollar sign, and cannot start with a number).
As Sentry.io explains, “Dot notation does have some limitations. If the key is dynamic, if it contains spaces or hyphens, or if it starts with a number you’ll get an error message.”
Bracket Notation Method
Bracket notation provides more flexibility and is essential when dealing with dynamic keys or keys that wouldn’t work with dot notation:
var obj = {key1: 'value1', key2: 'value2'};
obj['key3'] = 'value3';
The bracket notation method is particularly powerful because it allows you to use:
- Dynamic keys: Variables as property names
- Special characters: Keys with spaces, hyphens, or other special characters
- Numeric keys: Keys that start with numbers
- Reserved words: JavaScript reserved words as property names
According to GeeksforGeeks, “In this approach, we will directly access the key of an object by ‘.’ for assigning the value to it. It can be a repeated method as every time we need to define a different key for different values.” However, bracket notation solves the dynamic key limitation.
When to Use Each Method
Use Dot Notation When:
- You know the exact key name in advance
- The key is a valid JavaScript identifier
- You prefer cleaner, more readable code
- Performance is a critical concern (dot notation is faster)
// Good candidates for dot notation
obj.firstName = 'John';
obj.userAge = 25;
obj.isAdmin = true;
Use Bracket Notation When:
- The key is stored in a variable
- The key contains special characters or spaces
- The key starts with a number
- You need to access reserved words as properties
// Good candidates for bracket notation
obj['first name'] = 'John Doe'; // Space in key
obj['123-street'] = '123 Main St'; // Hyphen and number
obj['class'] = 'Mathematics'; // Reserved word
As FreeCodeCamp explains, “The reason for this is that Dot Notation only accepts static keys. So when you do obj.myKey, JavaScript looks for the property with the key myKey in obj. But that property does not exist, so we get undefined.”
Advanced Examples with Dynamic Keys
Using Variables as Keys
Bracket notation shines when you need to use variables as keys:
var obj = {key1: 'value1', key2: 'value2'};
var dynamicKey = 'key3';
var dynamicValue = 'value3';
obj[dynamicKey] = dynamicValue;
console.log(obj); // {key1: 'value1', key2: 'value2', key3: 'value3'}
Keys with Special Characters
var obj = {};
obj['user-profile'] = 'active'; // Hyphenated key
obj['full name'] = 'Alice Johnson'; // Space in key
obj['1st-place'] = 'Winner'; // Starts with number
console.log(obj);
Building Objects Dynamically
var user = {};
var fields = ['name', 'email', 'age'];
var values = ['Bob', 'bob@email.com', 30];
fields.forEach((field, index) => {
user[field] = values[index];
});
console.log(user); // {name: 'Bob', email: 'bob@email.com', age: 30}
According to SamanthaMing.com, “If you used the Dot notation, it will just assume you’re trying to access the property with a valid JavaScript identifier. Because it’s returning something, you might think everything is working fine. Under the hood, yes it is. But if your intention is to use the variable, it might throw you off.”
Common Mistakes to Avoid
1. Using Dot Notation with Dynamic Keys
This is a common mistake among beginners:
// ❌ Wrong approach
var key = 'key3';
obj.key = 'value3'; // This adds property 'key', not 'key3'
// ✅ Correct approach
var key = 'key3';
obj[key] = 'value3'; // This adds property 'key3'
2. Forgetting Quotes in Bracket Notation
Remember that bracket notation requires string literals (or variables):
// ❌ Wrong - missing quotes
obj[key3] = 'value3'; // ReferenceError: key3 is not defined
// ✅ Correct
obj['key3'] = 'value3'; // or obj[key3] if key3 is a variable
3. Using Dot Notation with Invalid Identifiers
// ❌ Wrong - invalid identifiers
obj.123key = 'value'; // SyntaxError
obj.my-key = 'value'; // SyntaxError
// ✅ Correct - use bracket notation
obj['123key'] = 'value';
obj['my-key'] = 'value';
Performance Considerations
Dot Notation is Faster
According to Stack Overflow, “Dot notation is faster (for me at least) test your browser jsperf.com/dot-notation-vs-bracket-notation/2”. This is because dot notation requires less processing at runtime - the property name is known at compile time.
When Performance Matters
In performance-critical applications, consider:
// Faster for static keys
for (let i = 0; i < 1000000; i++) {
obj.staticKey = i; // Dot notation
}
// Slower for dynamic keys
for (let i = 0; i < 1000000; i++) {
obj['dynamicKey' + i] = i; // Must use bracket notation
}
However, for most applications, the performance difference is negligible unless you’re processing millions of operations.
Conclusion
Adding key-value pairs to JavaScript objects is a fundamental operation that can be accomplished using either dot notation or bracket notation. Here are the key takeaways:
- Dot notation (
obj.key = value) is cleaner and faster but limited to valid JavaScript identifiers - Bracket notation (
obj['key'] = value) is more flexible and supports dynamic keys, special characters, and numeric keys - Use dot notation for static, valid identifiers when readability and performance are priorities
- Use bracket notation for dynamic keys, special characters, or when you need maximum flexibility
- Avoid the common mistake of using dot notation with variables - always use bracket notation for dynamic keys
When working with your specific object var obj = {key1: 'value1', key2: 'value2'}, you can add key3 with value3 using either obj.key3 = 'value3' or obj['key3'] = 'value3'. Choose the method that best fits your specific use case and coding style.
Sources
- How Can I Add a Key-Value Pair to a JavaScript Object? | Sentry
- How can I add a key/value pair to a JavaScript object? - Stack Overflow
- How to add Key-Value pair to a JavaScript Object? - GeeksforGeeks
- How to Add a Key/Value pair to an Object in JavaScript | bobbyhadz
- How to Add a Key Value Pair to a Javascript Object | Squash.io
- Dot Notation vs Bracket Notation for Object Properties – What’s the Difference? | FreeCodeCamp
- Dot notation vs Bracket notation | SamanthaMing.com
- Property accessors - JavaScript | MDN
- DOT & BRACKET Notation in JavaScript | CapsCode
- The differences between Dot Notation and Bracket Notation in Javascript | Medium