Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Represent Collision-free String Constants as Symbols in JavaScript

    Mike SherovMike Sherov

    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".



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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?"

    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.