How to set JavaScript object values dynamically?

JavaScript objects allow dynamic property assignment using bracket notation or dot notation. This enables you to set object values at runtime based on variables or user input.

Syntax

// Using dot notation
object.propertyName = value;

// Using bracket notation (dynamic)
object[propertyName] = value;
object['property name'] = value;

Method 1: Using Dot Notation

Dot notation works when you know the property name at compile time:






Dynamic Object Values






Click the button to see dynamic property updates

Method 2: Using Bracket Notation (Dynamic Keys)

Bracket notation allows property names to be determined at runtime:







Dynamic Property Assignment

Using Variables as Property Names








Comparison

Method Use Case Dynamic Keys Syntax
Dot Notation Known property names No obj.prop = value
Bracket Notation Dynamic/computed names Yes obj[key] = value
ES6 Computed Object literals Yes {[key]: value}

Common Use Cases

  • Form Data Processing: Setting object properties based on form field names
  • API Response Mapping: Dynamically assigning values from API responses
  • Configuration Objects: Building settings objects from user preferences
  • Dynamic Property Names: Creating properties with computed or variable names

Conclusion

Use dot notation for known properties and bracket notation for dynamic property assignment. Bracket notation provides flexibility when property names are determined at runtime or contain special characters.

Updated on: 2026-03-15T23:18:59+05:30

803 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements