0

Here is the code snippet I am trying to understand.

import { increment } from '../features/counter/counterSlice'
const object = {
  [increment]: () => {}
}
console.log(object)
// logs { "counter/increment": Function}

Specifically what does the following syntax do?

[increment]: () => {}

Increment is a reducer function created by createSlice().

  • creates an arrow function, named whatever the value of variable increment is, on `object` – Bravo Aug 13 '21 at 06:13
  • That syntax only does anything because it is inside an object. – QuentinUK Aug 13 '21 at 06:15
  • actually, `increment` is not *a reducer function*, it's a `string` – Bravo Aug 13 '21 at 06:19
  • @QuentinUK - much like a lot of syntax, validity does depend on context – Bravo Aug 13 '21 at 06:21
  • [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/q/2274242) | [Dynamic object property names?](https://stackoverflow.com/q/1798446) | [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/q/1184123) | [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/q/695050) – VLAZ Aug 13 '21 at 06:58
  • @Bravo - Yes your right. ```increment``` is a string. Thanks. – OG_On_The_Beat Aug 13 '21 at 21:34
  • @Bravo I'm reminded of "What is the “-->” operator in C/C++?" – QuentinUK Aug 24 '21 at 18:29

2 Answers2

2

This

const object = {
  [increment]: () => {}
}

is identical in result to

const object = {};
object[increment] = () => {};

In other words creates an arrow function, named whatever the value of variable increment is, on object

Bravo
  • 6,022
  • 1
  • 10
  • 15
2
const object = {
  [increment]: () => {}
}

This creates an object that has one property. The name of that property is defined by the string in the variable named increment. If increment had a value of "foo" then this would be equivalent to:

const object = {
  foo: () => {}
}

The value of that property is a function that does nothing.

An arrow function has this form

(...args) => { /* function body */ }

So () => {} is a function that takes no arguments, and has no statements in its function body.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337