Hacker News new | past | comments | ask | show | jobs | submit login

It's not an array, but a way of using a variable as a key in an object.

const name = "key"

const example = { [name]: "value" };

This would result in

const example = { key: "value" };




So if we know Symbol.dispose in advance we can simplify the code? Why did they make it so unwieldy especially since it is a new functionality not requiring backwards compatibility hacks?


Symbol.dispose is just a well-known symbol. Symbols are a fundamental part of the language, not a hack.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...


> So if we know Symbol.dispose in advance we can simplify the code?

Symbol.dispose is Symbol.dispose. It's a singleton object and that's the sole reference to it.

> Why did they make it so unwieldy especially since it is a new functionality not requiring backwards compatibility hacks?

1. Bare names in object keys are strings, so there needs to be an "escaping" syntax for non-string keys, that is what the brackets have done since 2015, in order to support the addition of...

2. Non-conflicting keys, which are what symbols are: symbols are guaranteed not to conflict with any string, and even to be unique unless they're created using `Symbol.for` (which accesses and stores into a global registry, this allows adding protocol methods to all objects without the risk of breaking existing any (by triggering new and unexpected behaviour).


> So if we know Symbol.dispose in advance we can simplify the code?

Symbol.dispose is not a string, but a symbol. Its value cannot be written out in the code, only referred to indirectly (that is basically what symbols are for), nor is there special syntax for properties with symbol keys like there is for properties with string keys, because that would be a nonsensical proposition due to the aforementioned fact. Thus, you cannot just write the property name directly, you have to use the computed property name syntax: [Symbol.dispose].


It wouldn't be any different:

    const dispose = Symbol.dispose
    const resource = { [dispose]: () => {...} }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: