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".
So, to follow up, why would you want to have collision free strings for this map of grades? Is there any benefit in this particular case?
Truth be told, Symbols as values as described in the lesson aren't particularly useful, but I kept it this way to keep the lesson clear.
But there are specific cases for collision free strings. Consider the following:
export const grades = [Symbol('A'), Symbol('B'), Symbol('C')];
export const isValidGrade = grade => grades.include(grade);
import { grades, isValidGrade } from 'grades.js';
const realASymbol = grades[0];
const otherASymbol = Symbol('A');
isValidGrade(realASymbol); // true
isValidGrade(otherASymbol); // false
isValidGrade('A'); //false
realASymbol.description; // 'A'
From the above, collision free symbols that can also represent strings provide guarantees that only the Symbol exported from the module counts as a valid grade, while allowing easy conversion to a string :-)
Cool, thanks for explanation ๐๐
This is a new concept to me, at least in JavaScript. (I've worked with Symbols a little in Ruby, but I'm not sure how they compare, and I can't claim I understand them well in Ruby, anyway.) I appreciate the additional explanation in the comments, @Mike Sherov, but I'm still struggling to understand why one would want to do this. Since 'a' === 'a'
, what difference could it make whether the 'a'
encountered is the "original one" added to the array or not?