Represent Collision-free String Constants as Symbols in JavaScript

Mike Sherov
InstructorMike Sherov
Share this video with your friends

Social Share Links

Send Tweet

ES2019 introduces the Symbol.prototype.description property. In this lesson, we'll learn why this property is useful and unlocks Symbols as appropriate to use to represent strings constants in JS. We'll investigate a use case for string constants and see why using Symbols prior to ES2019 was not appropriate. Then we'll see how using .description fixes that. Lastly, we'll learn why using Symbols may be better than strings for constants in certain use cases by examining what it means to be "collision free".

Instructor: [00:00] [inaudible] look at how we generate letter grades for our students, based upon the scores they've achieved in the class. If we go back to our transferARecord function inside of scores.vue, we see that once we generate the average for the student, we then pass [inaudible] getGrade function in order to get the letter grade for the student.

[00:17] What does the getGrade function look like? It's a pretty straightforward function that takes the numeric average in, and if it's greater than 95, returns an A. If it's greater than 85, returns a B. Otherwise, it returns a C. No students in this class ever get a D or an F.

[00:33] Prior to ES2019, we would just use strings. However, ES2019 opens us up to use symbols instead. Prior to ES2019, if I made A into a symbol, there'd be no way to get just the string "A" back out. As you could see over here, when I go to print out grades.a, it will print out the string "symbol(A)" and no way to get A itself.

[01:00] ES2019 adds a description property to symbols that returns the string that was passed to symbol creation. If I go ahead and turn these [inaudible] into symbols, our work is complete. You may want to ask yourself, "Why would I want to use a symbol here, rather than using a string?"

[01:27] The answer is, prior to ES2019, I wouldn't have. However, now that I have symbol description, I would use symbols wherever I had a string constant that I wanted to be collision-free. By collision-free, I mean symbol A <> symbol A. If I console.log this value, I can see that it returns false, whereas A=A is true.