2

I come cross this redux-actions tutorial, and I noticed a unusual syntax to create an object method:

const stringArray = ["STRING_ARRAY"];

const strangeObject = {
  [stringArray]() {
    console.log(stringArray);
  }
};

Can someone name or explain the syntax feature in use?

Salah Eddine Taouririt
  • 24,925
  • 20
  • 60
  • 96

1 Answers1

10

It's a mix of two features of ES6.

You can have computed property in an object:

const b = "foo";
const a = {
    [b]: true
};

// same as
const a = {};
a[b] = true;

There is also a shorthand for functions:

const a = {
    b() { console.log("foo");}
};

// same as
const a = {
    b: function() { console.log("foo");}
};

If you mix the two, you get what you have: a method whose name is a computed value. Here your object will be the same as

const strangeObject = {
    STRING_ARRAY: function() {
        console.log("STRING_ARRAY");
    }
};

Whenever a computed value for an object is not a string, as in your case, it will be converted to a string.

In your case

["STRING_ARRAY"].toString() === "STRING_ARRAY"

so it does not change much.

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
Axnyff
  • 9,213
  • 4
  • 33
  • 37
  • 1
    In your example (`[b]: true`), `b` is a string. What allows it to be an array and still work, like in OP's example? – mdatsev Jan 13 '18 at 15:23
  • 2
    It's `["STRING_ARRAY"].toString() === "STRING_ARRAY"` – Estus Flask Jan 13 '18 at 15:30
  • ^this and I think `String(["STRING_ARRAY"])` is more appropriate since you can do `[null]: true` and null doesn't have `.toString()` – mdatsev Jan 13 '18 at 15:33
  • @mdatsev ES6 allows [non-string object keys](https://stackoverflow.com/questions/6066846/keys-in-javascript-objects-can-only-be-strings). – Alex Jan 13 '18 at 21:51