Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Symbol type: (non-string object keys)

What is the "Symbol" javascript type as mentioned in this ECMAScript 6 draft specification?

To quote the spec:

The Symbol type is the set of all non-String values that may be used as the key of an Object property.

Each possible Symbol values is unique and immutable.

Symbol values have a single observable attribute called [[Private]] whose immutable value is either true or false. A private symbol is a Symbol value whose [[Private]] attribute has the value true.

I thought object keys were strings only, and I'm not alone. To quote this accepted SO answer:

…object keys are always strings…

Could you explain what the symbol type is, and demonstrate its usage. I'm trying to make sense of the spec.

Thanks!

like image 278
Web_Designer Avatar asked Jul 20 '13 07:07

Web_Designer


People also ask

Do JavaScript object keys have to be strings?

Restrictions in Naming Properties JavaScript object key names must adhere to some restrictions to be valid. Key names must either be strings or valid identifier or variable names (i.e. special characters such as - are not allowed in key names that are not strings).

Can object key be a symbol?

Symbols can be used as object keys. Only strings and symbols can be used as object keys. No two symbols are ever equal.

What's the type of a JavaScript object keys?

Keys in javascript objects can be strings and symbols. symbol is a primitive data type in javascript.


1 Answers

I thought object keys were strings only

You're right, but that was true for EcmaScript 5 only. ES 6 / harmony is a draft for something new!

I'm trying to make sense of the spec

It's a draft only, rapidly changing. How symbols are used and whether or how they can be created by arbitrary scripts does not seem to have settled yet (scan through the versions for changes).

If you scroll down to the very end of that document (even below Annex F), you for example will see a Section 8.4.4: Symbol Exotic Objects that has been moved out there. It states

Exotic Symbol objects provide alternative definitions for all of the essential internal methods.

You can see them used at section 8.1.7.4 Well-Known Symbols and Intrinsics for example. For proposed uses (and still existing problems / open questions) of Symbol constructors have a look at these strawman pages or this wiki site.

like image 68
Bergi Avatar answered Sep 23 '22 08:09

Bergi