Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add a property to a JavaScript object using a variable as the name?
In JavaScript, you can add properties to objects using either dot notation or bracket notation. However, when you need to use a variable as the property name, bracket notation is the only viable approach.
The Problem with Dot Notation
Dot notation treats everything after the dot as a literal property name, not a variable:
let obj = {a: "value1"};
let propertyName = "dynamicProp";
// This creates a property literally named "propertyName"
obj.propertyName = "value2";
console.log(obj);
console.log("Property 'dynamicProp' exists:", obj.dynamicProp); // undefined
{ a: 'value1', propertyName: 'value2' }
Property 'dynamicProp' exists: undefined
Using Bracket Notation with Variables
Bracket notation evaluates the expression inside the brackets, allowing you to use variables as property names:
let obj = {a: "value1"};
let propertyName = "dynamicProp";
// This uses the variable's value as the property name
obj[propertyName] = "value2";
console.log(obj);
console.log("Property 'dynamicProp' exists:", obj.dynamicProp);
{ a: 'value1', dynamicProp: 'value2' }
Property 'dynamicProp' exists: value2
Dynamic Property Names from User Input
This technique is particularly useful when property names come from variables, functions, or calculations:
let user = {};
let fields = ["name", "age", "email"];
let values = ["John", 25, "john@example.com"];
// Dynamically add properties using variables
for (let i = 0; i < fields.length; i++) {
user[fields[i]] = values[i];
}
console.log("User object:", user);
User object: { name: 'John', age: 25, email: 'john@example.com' }
Using Computed Property Names (ES6)
ES6 introduced computed property names in object literals using bracket syntax:
let prefix = "user";
let id = 123;
let propertyName = prefix + "_" + id;
// Computed property name in object literal
let obj = {
[propertyName]: "John Doe",
[`${prefix}_email`]: "john@example.com"
};
console.log(obj);
{ user_123: 'John Doe', user_email: 'john@example.com' }
Comparison
| Method | Static Property Names | Variable Property Names | Use Case |
|---|---|---|---|
| Dot Notation | ? | ? | Known property names |
| Bracket Notation | ? | ? | Dynamic property names |
| Computed Properties | ? | ? | Object literal creation |
Conclusion
Use bracket notation when you need to add properties with variable names. Dot notation only works with literal property names, while bracket notation evaluates expressions and supports dynamic property assignment.
