DEV Community

Cover image for What the heck is Computed Properties in JavaScript

What the heck is Computed Properties in JavaScript

Mohammed Awad on June 16, 2023

*Have you ever come across situations where you need to dynamically assign values to object properties * or perform computations based on dynamic p...
Collapse
 
blindfish3 profile image
Ben Calder • Edited

The example for "dynamic property names" is spurious and would never be done in practice: as already noted you should just use a static property name for such a generic property - i.e. isAdult.

I'm actually finding it very hard to find a practical example where this functionality might be needed; but I think I might have used it once or twice in the past 😅
You could perhaps use it to create a condensed data structure that is intended to be iterated with Object.entries()...

// in practice this data would probably be retrieved via an API:
const mySourceData = [
  { id: "foo", value: "something", /* many other properties */  },
  { id: "bar", value: "something else", /* many other properties */ },
];

// parsing to an array using destructuring to get relevant properties
const dataArray = mySourceData.map(({ id, value }) => ({ id, value }));

// parsing to an object
const dataObject = mySourceData.reduce((accumulator, { id, value }) => ({
    ...accumulator,
    [id]: value
}), {});    

console.log(dataArray);
console.log(dataObject);
Enter fullscreen mode Exit fullscreen mode

Both the map and reduce examples above are written in a condensed style I usually avoid since it hurts readability. For the reduce function I'd normally opt for "dynamic property assignment" since IMO that's clearer. i.e.:

accumulator[id] = value;
return accumulator;
Enter fullscreen mode Exit fullscreen mode

Dynamic property assignment is something I have definitely needed more frequently; but it's still something of a rarity.

Collapse
 
xmohammedawad profile image
Mohammed Awad

or maybe we can use Map() data strucure

Collapse
 
blindfish3 profile image
Ben Calder

To achieve what?

Thread Thread
 
xmohammedawad profile image
Mohammed Awad

instead of using dynamic property

Thread Thread
 
blindfish3 profile image
Ben Calder

In what context?
TBH it looks like you had some help writing the article; so I'm not sure what you're trying to achieve here 😅

Thread Thread
 
xmohammedawad profile image
Mohammed Awad • Edited

insted of using normal object we can use Map() insted If I need to use local variable or something like this . what you use insted of

    function handleChange(event) {
  const { name, value } = event.target;
        setMeme(prevMeme => ({
            ...prevMeme,
            [name]: value
        }))
    } 
Enter fullscreen mode Exit fullscreen mode

we can use

function handleChange(event) {
  const { name, value } = event.target;
  setMeme(prevMeme => {
    const updatedMeme = new Map(prevMeme);
    updatedMeme.set(name, value);
    return updatedMeme;
  });
}
Enter fullscreen mode Exit fullscreen mode


is this works??

Collapse
 
rokuem profile image
Mateus Amorim • Edited

when you mentioned computed properties I thought it was about object getters hehe, for what you did I would just call it a dynamic object key.

computed properties would be something like this (in my understanding):

const user = {
   firstName: "foo",
   secondName: "bar",
   get fullName() {
      return [user.firstName, user.secondName].join(" ");
   }
}

console.log(user.fullName) // "foo bar"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
xmohammedawad profile image
Mohammed Awad

I think you are correct. I just learned from course computed but then I saw people call it dynamic object key to be honest this name makes more sense

 
xmohammedawad profile image
Mohammed Awad

If I need to use local variable or something like this . what you use insted of [event.target.name]: value

    function handleChange(event) {
        setMeme(prevMeme => ({
            ...prevMeme,
            [event.target.name]: value
        }))
    }```


Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
endymion1818 profile image
Ben Read

In my experience this could be good for when you have to send custom events to an analytics platform such as Google Analytics or for simplifying the way an object is transformed - I came across somewhere I think this might have been useful where data was fetched from an api, modified by the user, then sent back to a different api that needed a different data structure. You never need it until you need it!

Collapse
 
xmohammedawad profile image
Mohammed Awad

should I use Map() data strucure then ?

Collapse
 
xmohammedawad profile image
Mohammed Awad

I'm still learning, can you tell me more, what is the best solution ?

Collapse
 
xmohammedawad profile image
Mohammed Awad

say Hi

 
rokuem profile image
Mateus Amorim • Edited

The example seems a little weird to me. Usually you report an analytics event by name, like this:

track(event.name, event.attributes);
Enter fullscreen mode Exit fullscreen mode

one thing to consider with dynamic keys too is the fact that it is a little harder to provide typescript types, meaning that if not done correctly, people will need to explore the code to understand what can be accessed.

In the "person" example that was provided in the post, this is how it would be typed:

function createPerson<T extends string>(name: T, age: number) {
  return {
    name,
    age,
    [`is${name}Adult`]: age >= 18
  };
}
Enter fullscreen mode Exit fullscreen mode

if you are not using typescript then it will be harder for others to know that the "person" has a "isAdult" property