Represent Collision-free String Constants as Symbols in JavaScript

Share this video with your friends

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

Jakub
Jakub
~ 5 years ago

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?

Mike Sherov
Mike Sherov(instructor)
~ 5 years ago

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:

grades.js

export const grades = [Symbol('A'), Symbol('B'), Symbol('C')];

export const isValidGrade = grade => grades.include(grade);

index.js

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 :-)

Jakub
Jakub
~ 5 years ago

Cool, thanks for explanation ๐Ÿ™‡๐Ÿ™‚

J. Matthew
J. Matthew
~ 5 years ago

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?