Lesson 13. Symbol—a new primitive
After reading lesson 13, you will
- Know how to use symbols as constants
- Know how to use symbols as object keys
- Know how to create behavior hooks with global symbols
- Know how to modify object behavior with well-known symbols
In JavaScript there are objects and there are primitives. The primitives of JavaScript are strings, numbers, Booleans (true or false), null, and undefined. Symbol is a new primitive added in ES2015 and is the first primitive added to JavaScript since its creation. A symbol is a unique value that’s used for hooking into the behavior of built-in JavaScript objects. Symbols can be broken into three categories:
- Unique symbols
- Global symbols
- Well-known symbols
Consider this
Imagine you were programming a chess game. You program the base chess piece with a moves() function that determines the available destinations, then checks if each is legal by checking if the destination is occupied by a teammate piece. The code for each type of chess piece needs to inherit from the base chess piece code. How would you make each chess piece override how the moves() function determines the possible destinations without overriding how it determines if the move is legal?