The Complete Guide to JS Symbols ES6

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
everyone it's cold I'm back thankfully not sick anymore or maybe maybe I was never sick maybe I was spending two weeks trying to grow a mustache and it looks so bad that I didn't want to be on camera so I lied and said I was sick it's possible but I actually was sick so this video is on JavaScript symbols a source of confusion amongst a lot of my students this video is pretty comprehensive but upfront I want to say there is one topic I don't cover around symbols because I'm gonna do a separate video on this topic which is iterators and well known symbols so there's something called well known symbols I don't go into it in this video but otherwise they cover everything else what else oh like this video please subscribe turn on notifications the past couple videos have done have all come from suggestions from subscribers and people who have notifications on so if you want to help sort of decide what comes next please subscribe okay let's get started symbols alright so let's start with the simplest question what the heck is a symbol so a symbol is a new primitive type in JavaScript just like we have number we've got string and we have boolean we now have a new member in that gang called symbol and you might be wondering well what exactly does it represent what is a symbol it is just a unique value of a special value that is going to be unique behind the scenes it's essentially you can think of it as like a really long number like this that is going to stay unique every time you make a new symbol so we use them in situations where we have to have a unique value usually when we're trying to avoid name conflicts between variables or not usually variable so usually properties keys in an object but we'll come back to that unlike these examples there is no nice literal shortcut syntax like to make a string usually we're just going to do this instead of string and typing it all out usually we don't do that same thing with number usually we don't do this it would just type the number 3 we have this shortcut that's not possible with symbol there is no shortcut syntax if you want to make a new symbol this is what you're going to type every time now you can optionally pass something in and we'll come back to that you can put something there but it doesn't really have an impact on the value of that symbol this is like a label this is good it's helpful for debugging for understanding what symbol is supposed to correspond to what but at the end of the day this is all you need every time you run this behind the scenes you're getting a special unique value all of these are going to be different that doesn't mean that they print out differently they look the same but behind the scenes they are not the same so let's prove that simply enough let's make a variable called sim one and set it equal to symbol and then duplicate that and just do sim two so these are both going to look the same when we print them out or return them in our case but if we test for equality they are not the same at all we get false so remember behind the scenes you can just think of giant numbers and they're guaranteed to be different except there's one caveat I'll come to at the end of this video there is a situation where you actually can generate symbols that aren't going to be unique but just to show you it this still applies if we pass in a descriptor a little label like this if I make two symbols where I pass in the string cat they're not equal once again they're totally different but it's it's still nice to pass those strings in because now when I look at sim one if I'm trying to understand what this symbol is it tells me this is a symbol and it sort of corresponds to cat but that doesn't mean that the symbol is is in some way based off of the string cat it doesn't use it in any way other than for debugging and making things clearer okay so with that out of the way what I want to talk about for most of this video is why you want these unique values why would you ever need a value like this there's really only one main thing people do with symbols which is to use them as the identifiers in object properties according to the docks and MDN this is their only purpose it's quite blunt so imagine we have some mystery objects that I've collapsed here we don't know what's in it let's say it's coming from some other source we're getting a bunch of different objects in and we want to add some unique ID to each one so we can keep track of them so if I just did user dot ID equals some thing like that that's going to be problematic because shocker there's already an idea in there who would have known and we just completely ignored it we over wrote it and it's gone so to avoid that situation this is contrived but imagine you know there are plenty of real-world scenarios where you need to add some property in and guarantee that it's not conflicting with something instead we could make a symbol so we could say I D symbol equals symbol pass in an optional description like that and then we just add it in as the key and then set that equal to whatever our ID looks like and now if we have user we have the original ID still there and then this symbol ID and so then to retrieve it we would just need to use this ID symbol so we want to save that reference and say user of ID symbol just like that and we get that ID back now if we wanted to do this in line as part of the object literal here and I wanted to say ID symbol right here just like that that's not going to work what actually happens is we end up with a string if we look at user it does add an ID symbol but it doesn't really realize that it's a symbol so the extra syntax looks like this we have to add those square brackets around it and now if we look at user you can see that it's gone back to being a symbol symbols were originally the idea was that they would allow for private properties in JavaScript that did not turn out this pretty much scrap that whole thing but it is important to note that symbols don't show up in a given object so if we do object dot get owned properties property names just like this and then we pass in user our ID symbol that's not there at all we get ID name city and age and if we looped over our object using a for in we also wouldn't see that symbol but we can find them though so they're not like secret entirely they're not private we can do get own property symbols and they show up we just pass in user and there we go so I just want to clear that up they are not private they're not you know hidden forever they're just not obvious let's put it that way now before I dive into use cases and showing you some slightly more complicated code though nothing is very complicated to be honest I do want to mention remember at the beginning I said symbols give you unique values but they're not always that's not always the case there's one caveat so you can do something called symbol dot for and symbol dot for is a method that will give you a symbol but it won't be unique for a given descriptor so I could say symbol dot for cat and every time I do symbol dot for cat so let's do Const sim1 equals symbol dot for cat and then duplicate it and do sim too those are being added to something called the global symbol space and if we look at them they look the same like always but if we do sim to they now are equivalent and just to verify that we'll do triple equals always better so when we do symbol dot four it is saying I want a global symbol and the idea is that we could then reference the symbol for cat later on often in a different eye frame so they're shared across iframes so if you need to communicate or share symbols this is how you would do that but otherwise if we're just doing symbol like this those are totally different unique values all right so let's talk about a couple of use cases here's one example where we're using what we will use symbols to represent concepts an idea something that's unique so in this case we have a function called get threat level it takes in a color and it returns like a string like severe high elevated depending on the color so the idea I guess it's based off of like the terrorism threat level scale something like that so we'd pass in red and they're all currently all these colors are strings which works except that they're not unique so something could happen potentially my cat her name happens to be blue I could pass in cat and to get threat level and still gets low which is what we would get when we pass in blue now that might not be a huge issue but what we could do instead is replace this replace all of these with symbols and now if we try and do get threat level if we pass in blue which is based off of a symbol we get low but if I pass in my cat which is the string blue we no longer get that it's totally different so we have these unique concepts that we can use okay so the next example is supposed to illustrate how you can use symbols to store metadata essentially in on an object so I have a class called train and it consists of a bunch of cars right so there's a refrigerator car full of cattle a tank car full of milk a hopper car full of coal and so on and I have a length that's sort of the metadata and the way it's set up right now is that it's just a regular old property but when I iterate over this and let's say I'm just printing everything out it's printing length and for I'm iterating over that and if I don't want that to happen what I could do is use a symbol just like this so I make a symbol save it to a variable and then I use that as the key I started at zero and then I add one to that property using the symbol to access it and now when I print everything out we skip over that because remember when we loop over an object symbols are not really included we can access them but we have to do it manually so those last two examples are a little bit niche this third one that I'm showing you is definitely the most common application which is to use symbols as keys to prevent name clashes or collisions so this is based off of a real thing just very very simplified but imagine we're working on a website we have a bunch of components it doesn't matter what they are but imagine you know - dues and lists and buttons and forms and modal's and tomsy components and at any point there could be a problem an issue with one of them and so we have an alert service to manage all of those alerts and basically keep track of them and then remove them as they need to be removed so alert service is just really simple it's just an object with a way of adding and removing alerts what's important is down here in my component each time we make a new components it gets a special component ID which is a symbol so I might have two different list components but they have entirely different that they look the same but they have entirely different symbols different IDs and so that way if it so happens that both of them have problems at the same time they both can be inside of our alert service with no issue so if I call this error hand function all that it does is take that component ID and add an alert into our alert service using that ID with a message if we look at that alert service it's not very exciting but we can see that there are two alerts both symbol list component but they're unique so if this is all happening dynamically or maybe this is animations or we're working with the cache and we don't know what's in there ahead of time this is a way we can use symbols to create these unique IDs so we can add something and don't have to worry about overwriting something there's no conflict there couldn't be a conflict and then the second part of this just to illustrate it we can use that symbol that component ID to remove them back out which I just did with set timeout so if we take a look right now there should be two things in there and then they're both removed using those IDs and there's no conflict there's no issue and now it's empty so silly simple example but it's based in truth it's based in reality we use these symbols to create unique IDs so that we can add something in totally unique keys no conflict no threat of overwriting things okay hopefully that makes sense
Info
Channel: Colt Steele
Views: 31,263
Rating: 4.9533257 out of 5
Keywords: symbols, js, javascript, es6, es2016, es2017
Id: 4J5hnOCj69w
Channel Id: undefined
Length: 12min 18sec (738 seconds)
Published: Fri Jan 11 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.