google / google/closure-compiler
Computed object keys produce very odd output
- Dominant language
- JavaScript
- Stars
- 7.7k
- Forks
- 1.2k
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 6
Description
Hi, I'm seeing some strange-looking output when using square brackets to quote object keys.
```js
const a = { ['foo']: 1};
const b = { ['bar']: 2};
console.log(a, b);
```
becomes:
```js
var a={},b=(a.foo=1,a),c={},d=(c.bar=2,c);console.log(b,d);
```
[Appspot link here](https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540compilation_level%2520ADVANCED_OPTIMIZATIONS%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250A%252F%252F%2520ADD%2520YOUR%2520CODE%2520HERE%250Aconst%2520a%2520%253D%2520%257B%2520%255B'foo'%255D%253A%25201%257D%253B%250Aconst%2520b%2520%253D%2520%257B%2520%255B'bar'%255D%253A%25202%257D%253B%250Aconsole.log(a%252C%2520b)%253B%250A%250A). It gets worse: more intermediary objects are created as you add more keys.
I'd expect the result to be closer to the setup without `[]`, i.e.:
```js
console.log({foo:1},{bar:2});
```
----
Further context: this came about as we're looking to use [Prettier](https://prettier.io) to format code in our project, but can't easily do so as it unquotes keys that don't strictly need to be quoted. This breaks instances where we need quoted keys not to be mangled by Closure Compiler.
One of the workaround people are using is `{ ['foo']: bar }` syntax, which Prettier won't unquote, but that produces bad output when fed into CC.
Contributor guide
Assessment
This issue has not been assessed yet.