5

Notes about 'Not a duplicate':

I've been told this is a duplicate of What is the use of Symbol in javascript ECMAScript 6?. Well, it doesn't seem right to me. The code they've given is this:

const door = {};
// library 1
const cake1 = Symbol('cake');
door[cake1] = () => console.log('chocolate');
// library 2
const cake2 = Symbol('cake');
door[cake2] = () => console.log('vanilla');
// your code
door[cake1]();
door[cake2]();

The only thing that makes this work is because cake1 and cake2 are different (unique) names. But the developer has explicitly given these; there is nothing offered by Symbol which helps here.

For example if you change cake1 and cake2 to cake and run it, it will error:

Uncaught SyntaxError: Identifier 'cake' has already been declared

If you're already having to manually come up with unique identifiers then how is Symbol helping?

If you execute this in your console:

Symbol('cake') === Symbol('cake');

It evaluates to false. So they're unique. But in order to actually use them, you're now having to come up with 2 key names (cake1 and cake2) which are unique. This has to be done manually by the developer; there's nothing in Symbol or JavaScript in general which will help with that. You're basically creating a unique identifier using Symbol but then having to assign it manually to...a unique identifier that you've had to come up with as a developer.

With regards to the linked post they cite this as an example which does not use Symbol:

const door = {};
// from library 1
door.cake = () => console.log('chocolate');
// from library 2
door.cake = () => console.log('vanilla');

// your code
door.cake();

They try to claim this is a problem and will only log "vanilla". Well clearly that's because door.cake isn't unique (it's declared twice). The "fix" is as simple as using cake1 and cake2:

door.cake1 = () => console.log('chocolate');
door.cake2 = () => console.log('vanilla');

door.cake1(); // Outputs "chocolate"
door.cake2(); // Outputs "vanilla"

That will now work and log both "chocolate" and "vanilla". In this case Symbol hasn't been used at all, and indeed has no bearing on that working. It's simply a case that the developer has assigned a unique identifier but they have done this manually and without using Symbol.


Original question:

I'm taking a course in JavaScript and the presenter is discussing Symbol.

At the beginning of the video he says:

The thing about Symbol's is that every single one is unique and this makes them very valuable in terms of things like object property identifiers.

However he then goes on to say:

  1. They are not enumerable in for...in loops.
  2. They cannot be used in JSON.stringify. (It results in an empty object).

In the case of point (2) he gives this example:

console.log(JSON.stringify({key: 'prop'})); // object without Symbol
console.log(JSON.stringify({Symbol('sym1'): 'prop'})); // object using Symbol

This logs {"key": "prop"} and {} to the console respectively.

How does any of this make Symbol "valuable" in terms of being unique object keys or identifiers?

In my experience two very common things you'd want to do with an object is enumerate it, or convert the data in them to JSON to send via ajax or some such method.

I can't understand what the purpose of Symbol is at all, but especially why you would want to use them for making object identifiers? Given it will cause things later that you cannot do.

Edit - the following was part of the original question - but is a minor issue in comparison to the actual purpose of Symbol with respect to unique identifiers:

If you needed to send something like {Symbol('sym1'): 'prop'} to a backend via ajax what would you actually need to do in this case?

Andy
  • 5,142
  • 11
  • 58
  • 131
  • "*If you needed to send something like `[Symbol('sym1'): 'prop']` to a backend via ajax what would you actually need to do in this case?*" the question seems to be coming from a completely wrong direction. Because 1. You *wouldn't* be sending Symbol properties via AJAX. 2. You *shouldn't* be sending Symbol properties via AJAX. These are two similar sounding concepts but quite distinct. The JSON format has no support for Symbols, so you simply cannot do it. And Symbols are not intended to be transferable anyway but local to the current system only – VLAZ Jan 16 '20 at 11:25
  • That isn't explained in the video at all so thanks for the information. I can't understand why the presenter is discussing `JSON.stringify` with respect to `Symbol`'s then. Still also unclear on them being "valuable" as identifiers. – Andy Jan 16 '20 at 11:26
  • 1
    Put the other way around: you'd be using Symbols if you explicitly wanted to prevent them from being JSON serialised, or generally if you want them to be inaccessible to anything but your code at runtime. – deceze Jan 16 '20 at 11:36
  • Re "Re not a duplicate": …?! Symbols have nothing to do with even attempting to solve that problem?! That error message occurs because you have the same `const cake` declaration twice. That's a mechanism of `const` and has nothing to do with Symbols per se. – deceze Jan 16 '20 at 12:01
  • @deceze `Symbol('cake');` produces 2 unique identifiers in the above code. But in order to reference them you have to assign them to 2 uniquely named variables (`cake1` and `cake2`). My question is asking exactly that - if you have to create uniquely named variables then how does `Symbol` actually do anything of any value? It isn't creating the unique names `cake1` and `cake2` because the developer has had to manually figure out and assign those themselves. It's basically just assigning a unique identifier....to...a *manually created* unique identifier! – Andy Jan 16 '20 at 12:44
  • Yes, that now basically means the accessibility of those symbols plays by the same rules as variable scope. Even if you pass an object around between different scopes, you can only access symbol properties of it through variables which are in a particular scope. It’s a form of *private properties*, as the duplicate says. – deceze Jan 16 '20 at 12:56
  • Consider that you can also use other ways to store those symbols, like `const props = [Symbol('foo'), ...]`. But usually you'd probably declare one or two symbols as variable at the top of your module which you'll use again and again. I'd probably declare them like constants, e.g. `const IMPORTANT_PROP = Symbol('foo')`. – deceze Jan 16 '20 at 13:42
  • *”They try to claim this is a problem and will only log "vanilla". Well clearly that's because door.cake isn't unique”* — Yes. That is a simplified example to demonstrate the point. What if **two independent modules** were trying to declare `.cake` on the same object!? You can’t reliably resolve those naming issues cross-module or cross-library. Which one gets to use `.cake1` and which one `.cake2`? The only way is to declare the property with a guaranteed unique Symbol…! – deceze Jan 16 '20 at 17:21

4 Answers4

3

I replied to your comment in the other question, but since this is open I'll try to elaborate.

You are getting variable names mixed up with Symbols, which are unrelated to one another.

The variable name is just an identifier to reference a value. If I create a variable and then set it to something else, both of those refer to the same value (or in the case of non-primitives in JavaScript, the same reference).

In that case, I can do something like:

const a = Symbol('a');
const b = a;

console.log(a === b); // true

That's because there is only 1 Symbol created and the reference to that Symbol is assigned to both a and b. That isn't what you would use Symbols for.

Symbols are meant to provide unique keys which are not the same as a variable name. Keys are used in objects (or similar). I think the simplicity of the other example may be causing the confusion.

Let us imagine a more complex example. Say I have a program that lets you create an address book of people. I am going to store each person in an object.

const addressBook = {};

const addPerson = ({ name, ...data }) => {
  addressBook[name] = data;
};

const listOfPeople = [];

// new user is added in the UI
const newPerson = getPersonFromUserEntry();

listOfPeople.push(newPerson.name);
addPerson(newPerson);

In this case, I would use listOfPeople to display a list and when you click it, it would show the information for that user.

Now, the problem is, since I'm using the person's name, that isn't truly unique. If I have two "Bob Smith"'s added, the second will override the first and clicking the UI from "listOfPeople" will take you to the same one for both.

Now, instead of doing that, lets use a Symbol in the addPerson() and return that and store it in listOfPeople.

const addressBook = {};

const addPerson = ({ name, ...data }) => {
  const symbol = Symbol(name);

  addressBook[symbol] = data;

  return symbol;
};

const listOfPeople = [];

// new user is added in the UI
const newPerson = getPersonFromUserEntry();

listOfPeople.push(addPerson(newPerson));

Now, every entry in listOfPeople is totally unique. If you click the first "Bob Smith" and use that symbol to look him up you'll get the right one. Ditto for the second. They are unique even though the base of the key is the same.

As I mentioned in the other answer, the use-case for Symbol is actually fairly narrow. It is really only when you need to create a key you know will be wholly unique.

Another scenario where you might use it is if you have multiple independent libraries adding code to a common place. For example, the global window object.

If my library exports something to window named "getData" and someone has a library that also exports a "getData" one of us is going to override the other if they are loaded at the same time (whoever is loaded last).

However, if I want to be safer, instead of doing:

window.getData = () => {};

I can instead create a Symbol (whose reference I keep track of) and then call my getData() with the symbol:

window[getDataSymbol]();

I can even export that Symbol to users of my library so they can use that to call it instead.

(Note, all of the above would be fairly poor naming, but again, just an example.)

Also, as someone mentioned in the comments, these Symbols are not for sharing between systems. If I call Symbol('a') that is totally unique to my system. I can't share it with anyone else. If you need to share between systems you have to make sure you are enforcing key uniqueness.

samanime
  • 25,408
  • 15
  • 90
  • 139
  • This is a great answer so thanks for putting the effort into it. I disagree that I was confusing variable names though. I understand how assignment works but my point was that if you're doing things (in the OP) like `const cake1 = Symbol('cake');` and `const cake2 = Symbol('cake');` **the actual variable names** (`cake1` and `cake2`) **are unique**. Therefore you could have just done `const cake1 = 'cake1'` and `const cake2 = 'cake2'` to produce 2 unique references, since `'cake1' === 'cake2'` would evaluate to `false` much like using `Symbol`. – Andy Jan 17 '20 at 09:44
  • I'm more of a backend developer but I also don't understand why you would ever use a non-unique key such as name (`addressBook[name]`) in the first place? In backend systems you'd almost always use a unique ID (often an auto-incrementing value in a database) to identify each record. So even if you had 100 Bob Smith's it wouldn't matter, and that's exactly the point. Is `Symbol` an attempt to solve this in a client-side environment where you aren't necessarily connecting to a database or storage engine with unique keys to identify references? – Andy Jan 17 '20 at 09:51
  • Somewhat... Like I said, the use-case is generally fairly limited in the first place. I think it was mainly created so multiple people/ibrary could set libraries in the global scope where they might have conflicts and still have them both exist and work properly. – samanime Jan 17 '20 at 16:09
  • In response to your first comment, yes, you could have in this case, but the idea with Symbol would be `cake1` might be created by person A and `cake2` might be created by person B (two separate libraries) and you don't know what each is going to name it, so you don't know ahead of time that they aren't both just going to call it "cake". – samanime Jan 17 '20 at 16:13
1

To expand on @samanime's excellent answer, I'd just like to really put emphasis on how Symbols are most commonly used by real developers.

Symbols prevent key name collision on objects.

Let's inspect the following page from MDN on Symbols. Under "Properties", you can see some built-in Symbols. We'll look at the first one, Symbol.iterator.

Imagine for a second that you're designing a language like JavaScript. You've added special syntax like for..of and would like to allow developers to define their own behavior when their special object or class is iterated over using this syntax. Perhaps for..of could check for a special function defined on the object/class, named iterator:

const myObject = {
  iterator: function() {
    console.log("I'm being iterated over!");
  }
};

However, this presents a problem. What if some developer, for whatever reason, happens to name their own function property iterator:

const myObject = {
  iterator: function() {
    //Iterate over and modify a bunch of data
  }
};

Clearly this iterator function is only meant to be called to perform some data manipulation, probably very infrequently. And yet if some consumer of this library were to think myObject is iterable and use for..of on it, JavaScript will go right ahead and call that function, thinking it's supposed to return an iterator.

This is called a name collision and even if you tell every developer very firmly "don't name your object properties iterator unless it returns a proper iterator!", someone is bound to not listen and cause problems.


Even if you don't think just that one example is worthy of this whole Symbol thing, just look at the rest of the list of well-known symbols. replace, match, search, hasInstance, toPrimitive... So many possible collisions! Even if every developer is made to never use these as keys on their objects, you're really restricting the set of usable key names and therefore developer freedom to implement things how they want.

Symbols are the perfect solution for this. Take the above example, but now JavaScript doesn't check for a property named "iterator", but instead for a property with a key exactly equal to the unique Symbol Symbol.iterator. A developer wishing to implement their own iterator function writes it like this:

const myObject = {
  [Symbol.iterator]: function() {
    console.log("I'm being iterated over!");
  }
};

...and a developer wishing to simply not be bothered and use their own property named iterator can do so completely freely without any possible hiccups.

This is a pattern developers of libraries may implement for any unique key they'd like to check for on an object, the same way the JavaScript developers have done it. This way, the problem of name collisions and needing to restrict the valid namespace for properties is completely solved.



Comment from the asker:

The bit which confused me on the linked OP is they've created 2 variables with the names cake1 and cake2. These names are unique and the developer has had to determine them so I didn't understand why they couldn't assign the variable to the same name, as a string (const cake1 = 'cake1'; const cake2 = 'cake2'). This could be used to make 2 unique key names since the strings 'cake1' !== 'cake2'. Also the answer says for Symbol you "can't share it" (e.g. between libraries) so what use is that in terms of avoiding conflict with other libraries or other developers code?

The linked OP I think is misleading - it seems the point was supposed to be that both symbols have the value "cake" and thus you technically have two duplicate property keys with the name "cake" on the object which normally isn't possible. However, in practice the capability for symbols to contain values is not really useful. I understand your confusion there, again, I think it was just another example of avoiding key name collision.

About the libraries, when a library is published, it doesn't publish the value generated for the symbol at runtime, it publishes code which, when added to your project, generates a completely unique symbol different than what the developers of the library had. However, this means nothing to users of the library. The point is that you can't save the value of a symbol, transfer it to another machine, and expect that symbol reference to work when running the same code. To reiterate, a library has code to create a symbol, it doesn't export the generated value of any symbols.

Klaycon
  • 10,599
  • 18
  • 35
  • Thanks. The bit which confused me on the linked OP is they've created 2 variables with the names `cake1` and `cake2`. These *names* are unique and the developer has had to determine them so I didn't understand why they couldn't assign the variable to the same name, as a string (`const cake1 = 'cake1'; const cake2 = 'cake2'`). This could be used to make 2 unique *key names* since the strings `'cake1' !== 'cake2'`. Also the answer says for `Symbol` you "can't share it" (e.g. between libraries) so what use is that in terms of avoiding conflict with other libraries or other developers code? – Andy Jan 17 '20 at 10:47
1

As a very practical example what kind of problem Symbols solve, take 's use of $ and $$:

AngularJS Prefixes $ and $$: To prevent accidental name collisions with your code, AngularJS prefixes names of public objects with $ and names of private objects with $$. Please do not use the $ or $$ prefix in your code.
https://docs.angularjs.org/api

You'll sometimes have to deal with objects that are "yours", but that Angular adds its own $ and $$ prefixed properties to, simply as a necessity for tracking certain states. The $ are meant for public use, but the $$ you're not supposed to touch. If you want to serialise your objects to JSON or such, you need to use Angular's provided functions which strip out the $-prefixed properties, or you need to otherwise be aware of dealing with those properties correctly.

This would be a perfect case for Symbols. Instead of adding public properties to objects which are merely differentiated by a naming convention, Symbols allow you to add truly private properties which only your code can access and which don't interfere with anything else. In practice Angular would define a Symbol once somewhere which it shares across all its modules, e.g.:

export const PRIVATE_PREFIX = Symbol('$$');

Any other module now imports it:

import { PRIVATE_PREFIX } from 'globals';

function foo(userDataObject) {
    userDataObject[PRIVATE_PREFIX] = { foo: 'bar' };
}

It can now safely add properties to any and all objects without worrying about name clashes and without having to advise the user about such things, and the user doesn't need to worry about Angular adding any of its own properties since they won't show up anywhere. Only code which has access to the PRIVATE_PREFIX constant can access these properties at all, and if that constant is properly scoped, that's only Angular-related code.

Any other library or code could also add its own Symbol('$$') to the same object, and it would still not clash because they're different symbols. That's the point of Symbols being unique.

(Note that this Angular use is hypothetical, I'm just using its use of $$ as a starting point to illustrate the issue. It doesn't mean Angular actually does this in any way.)

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Small nitpick: `Only code which has access to the PRIVATE_PREFIX constant can access these properties at all` isn't strictly true, the devs made it fairly easy to simply iterate symbol properties on any given object with `Object.getOwnPropertySymbols()` – Klaycon Jan 17 '20 at 15:14
  • Okay, you can go out of your way to access that data explicitly. Just as you can with `private` properties in most languages implementing such a thing. But you *know* if you do that, it's not that you'll accidentally do it. – deceze Jan 17 '20 at 15:16
0

What's the purpose of Symbol in terms of unique object identifiers?

Well,

Symbol( 'description' ) !== Symbol( 'description' )

How does any of this make Symbol "valuable" in terms of being unique object keys or identifiers?

In a visitor pattern or chain of responsibility, some logic may add additional metadata to any object and that's it (imagine some validation OR ORM metadata) attached to objects but that does not persist *.

If you needed to send something like {Symbol('sym1'): 'prop'} to a backend via ajax what would you actually need to do in this case?

If I may assure you, you won't need to do that. you would consider { sym1: 'prop' } instead.


Now, this page even has a note about it

Note: If you are familiar with Ruby's (or another language) that also has a feature called "symbols", please don’t be misguided. JavaScript symbols are different.

As I said, there are useful for runtime metadata and not effective data.

Salathiel Genese
  • 1,639
  • 2
  • 21
  • 37