Lessons from open-source: Use Symbol in Javascript to avoid name collisions
This lesson is picked from next.js/packages/next. In this article, you will learn what a Symbol is, how Next.js uses Symbol, some other repositories that use Symbol in the Github wilderness and further reading references
In JavaScript, a Symbol is a unique and immutable data type introduced in ECMAScript 6 (ES6). Unlike other primitive data types like strings or numbers, Symbols are guaranteed to be unique, making them useful for creating keys in objects that need to avoid naming collisions. Symbols can be used to define properties with special meanings or to create private members within objects (But they are not entirely private, you can access symbols using Object.getOwnPropertySymbols).
// Creating a Symbolconst mySymbol = Symbol('uniqueSymbol');// Using the Symbol as a property keyconst myObject = {[mySymbol]: 'This is a value associated with mySymbol',};// Accessing the property using the Symbolconsole.log(myObject[mySymbol]); // Output: This is a value associated with mySymbolconsole.log("Object.getOwnPropertySymbols", Object.getOwnPropertySymbols);
You can also search for “Symbol” on Github with a language filter set to Javascript, you will find some popular repositories that use Symbol in their codebase.
As you can see, it is well known data type used in popular repos such as webpack, svelte, mongo etc.,
In conclusion, Symbols in JavaScript are unique and immutable data types introduced in ECMAScript 6 (ES6). Unlike other primitive data types, Symbols guarantee uniqueness, making them useful for creating keys in objects to avoid naming collisions. Next.js uses Symbols to prevent name collisions with helper functions and keys.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.