TypeOfNaN

How to access an object property with a dynamically-computed name in JavaScript

Nick Scialli
March 18, 2023

New — Check out my free newsletter on how the web works!

Using a dynamic object key name is critical for creating dynamic JavaScript applications. Let’s consider the following object that represents a person:

const person = {
  name: 'Wilma',
  age: 27,
};

Dot notation doesn’t work

If we know what key we need to access, we can simply use dot notation to get it. For example, we can console.log ther person’s name:

console.log(person.name);
// Wilma

But what if we have a variable that represents the key we want? In our example, that variable can be either "name" or age:

const person = {
  name: 'Wilma',
  age: 27,
};

const key = 'age';

We can’t use dot notation in this instance. Trying to get person.key will fail because JavaScript will look for a key property on person, which doesn’t exist.

Bracket notation works!

Fortunately, we can use bracket notation in this case: person[key]

const person = {
  name: 'Wilma',
  age: 27,
};

const key = 'age';

console.log(person[key]);
// 27

And there you have it! You can now use a dynamic key to access a property on a JavaScript object.

🎓 Learn how the web works

One of the best ways to level up your tech career is to have a great foundational understanding of how the web works. In my free newsletter, How the Web Works, I provide simple, bite-sized explanations for various web topics that can help you boost your knowledge. Join 2,500+ other learners on the newsletter today!

Signing up is free, I never spam, and you can unsubscribe any time. You won't regret it!

Sign up for the newsletter »
Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli