So in Lisp/Scheme, there are these ‘symbols’, which are basically, if I understand correctly, and correct me if I’m wrong, references to variables (not their values). I was wondering if there’s a JavaScript equivalent to that?
Thank you!
So in Lisp/Scheme, there are these ‘symbols’, which are basically, if I understand correctly, and correct me if I’m wrong, references to variables (not their values). I was wondering if there’s a JavaScript equivalent to that?
Thank you!
2
Answers
In JavaScript, the closest equivalent to Lisp’s symbols are actually symbols themselves, introduced in ES6. JavaScript’s Symbol type represents unique, immutable identifiers. They can be used as keys for object properties, ensuring no accidental name conflicts with other property names, but they aren’t exactly like Lisp symbols in terms of variable references.
Here’s a breakdown of how Symbol in JavaScript compares to Lisp symbols and what it can and can’t do:
Uniqueness and Identity:
In JavaScript, each Symbol created is unique, which aligns with how Lisp symbols can serve as unique identifiers. For example:
Even if two symbols have the same description, they are unique.
No Direct Reference to Variables:
Lisp symbols can refer to variable names or functions in the global environment. JavaScript symbols, however, don’t directly link to variables or hold references to values. They are more like keys that don’t collide with other keys. This means you can’t use Symbol to refer to a variable in the same way a Lisp symbol can refer to a binding.
Usage as Object Keys:
JavaScript Symbols are often used as property keys in objects to create “hidden” properties that don’t interfere with other keys. Here’s how you might use them:
Workarounds for Variable Reference Behavior
If you want something closer to Lisp-like behavior (e.g., symbolic names that refer to variables), you might use string keys in a map or even an object with property names that hold variable values. For example:
This won’t give you true symbolic manipulation, but it allows you to indirectly reference variables by their names.
In summary:
JavaScript Symbol provides unique identifiers, useful for keys in objects but without the variable-binding references Lisp offers.
You can simulate references with object properties or a map, though this approach lacks Lisp’s symbolic manipulation capabilities.
Symbols in Common Lisp are a made of a name, a package, and a property list.
They are not necessarily "references to variables", but this is one of the possible uses of symbols. Symbols are efficient because they are interned when reading the source code, meaning that the same combination of name and package object refers to the same symbol.
Global variables and functions can be referenced by their identifiers, which are symbols. But symbols can also be used without being tied to variables or functions.