Sling Academy
Home/JavaScript/JavaScript: Create/Access Object Properties with Variable Keys

JavaScript: Create/Access Object Properties with Variable Keys

Last updated: March 22, 2023

In JavaScript, you can create and access object properties dynamically by using variable keys. This allows you to create more dynamic and flexible code. In this short and straightforward article, we will explore more than one way to do so.

Using bracket notation

The bracket notation allows you to use any expression as a property name, such as a variable or a string concatenation.

Example:

const obj = {
    name: 'Demon of Hatred',
};

// a key can be a variable
const key = 'age';

// add a new property whose key is a variable
obj[key] = 999;

// access the property using the variable
console.log(obj[key]); 

Output:

999

Using computed property names

In modern JavaScript (ES6 and above), you can use computed property names, which lets you use an expression inside square brackets after the object literal, to create or access an object’s properties by variable keys.

Example:

// define variables for the keys
const key1 = 'name';
const key2 = 'age';

// create an object with computed property names
const obj = { 
    [key1]: 'Sling Academy',
    [key2]: 5
};

// access the properties using bracket notation
console.log(obj[key1]);
console.log(obj[key2]);

Output:

Sling Academy
5

Using Object.defineProperty()

This method can help you define a new property on an object or modify an existing one. You can use this method to create a property with a dynamic key by passing an expression as the second argument.

Example:

// the starting object
const obj = {
    name: 'Voldermort',
}; 

// define a variable for the key
const key = 'age'; 

// create a property with a dynamic key and value
Object.defineProperty(obj, key, { value: 60 }); 

// access the property using bracket notation
console.log(obj[key]);

Output:

60

Using the Object.defineProperty() method is a little verbose because it requires a descriptor object as the third argument. In addition, it has some limitations, such as not working on non-extensible objects. I put this approach here for your preference, but I think you better use one of the first 2 approaches.

If you wonder what is a non-extensible object in JavaScript, then here’s an example:

// create an object
var obj = { name: "Wolf", age: 35 }; 

// make it non-extensible
Object.preventExtensions(obj); 

 // this throws a TypeError
Object.defineProperty(obj, "gender", { value: "male" });

console.log(obj); 
// TypeError: can't define property "gender": "obj" is not extensible

The tutorial ends here. Happy coding & have a nice day!

Next Article: JavaScript: Checking if a Key/Value Exists in an Object

Previous Article: JavaScript: Get the Key of an Object Property by Its Value

Series: Working with Objects in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration