DEV Community

Cover image for πŸ’‘ How to dynamically create and access properties on JavaScript objects
Benjamin Mock
Benjamin Mock

Posted on β€’ Originally published at codesnacks.net

5 2

πŸ’‘ How to dynamically create and access properties on JavaScript objects

Today we'll learn how to dynamically create and access properties on JS objects.

There are two ways to set and access properties on objects:

  • the do notation
  • the bracket notation

Let's see these in action:

// create an empty object
const pastry = {}

// set a name property on the object using the dot notation
pastry.name = "waffle"

// set a deliciousness property on the object using the bracket notation
pastry["deliciousness"] = 11

// you can also use both notations to access properties again
console.log(pastry.deliciousness) // 11
console.log(pastry["name"]) // waffle

But how would we dynamically set and read these properties? Let's say we would have the name of the property in a variable?

An example could be a get or a set method in which you can pass an object and a property. The set would of course also take a value.

Let's see these functions:

function get(obj, prop) {
  // return prop on obj
}

function set(obj, prop, value) {
  // set value for prop on obj
}

// create an empty object
const pastry = {};

// use set
set(pastry, "name", "waffle")

// use get
console.log(get(pastry, "name")

So how would it work? We can use the bracket notation to dynamically set and get properties.

function get(obj, prop) {
  // return prop on obj
  return obj[prop]
}

function set(obj, prop, value) {
  // set value for prop on obj
  obj[prop] = value
}

// create an empty object
const pastry = {};

// use set
set(pastry, "name", "waffle")

// use get
console.log(get(pastry, "name")) // waffle

Want to get better at Web Development?
πŸš€πŸš€πŸš€subscribe to the Tutorial Tuesday βœ‰οΈnewsletter

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (1)

Collapse
 
imshivanshpatel profile image
SHIVANSH PATEL β€’

Helpful

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’