I said ‘moo’ to this cow but it didn’t appear to understand. Alas I don’t speak cow Hindi.

Computed property names FTW!

Dave Sag
codeburst

--

I’ve been coding Javascript for 20 years and every day I discover something new about the language.

Today I discovered this:

const key = 'hello'const things = { [key]: 'world' }==> things is { hello: ‘world’ }

Why is this useful?

Up until now I’ve been doing this instead

const key = 'hello'const things = {}things[key] = 'world'

Why would I do that?

const inject = (key, val, other = {}) => { ...other, [key]: val }

is a lot neater than

const inject = (key, value, other = {}) => {  const result = { ...other }  result[key] = value  return result}

Obviously this is a trivial and mostly pointless example but the general idea of being able to inject a dynamic key into an object is pretty damn powerful and I’ve been doing it the long way around since forever.

Read more about Computed property names.

Like this but not a subscriber? You can support the author by joining via davesag.medium.com.

--

--