What is the purpose of the dollar sign in JavaScript?
The $ in JavaScript is a convention, without any special meaning to the JavaScript interpreter. In libraries, such as jQuery, it denotes jQuery objects using $(selector). Outside libraries, you can use it at your discretion as a convention. Moreover, in modern JavaScript, $ pulls double duty with template literals, providing ${expression} syntax for dynamic string creation.
$ and JavaScript identifiers
Dollar diving in frameworks
In JavaScript, the $ sign can prefix identifiers such as variable and function names. It is often used in machine-generated code or within specific JavaScript frameworks to denote unique functions or modules.
Frameworks usage:
- Prototype & jQuery: Uses
$for utility functions like element selector. - AngularJS: Add a
$before AngularJs-provided services, like$http, to differentiate from user defined variables.
Taking literals to a new level
With ECMAScript 6 (ES6), $ became integral in template literals for embedding expressions and creating dynamic strings. It's also used in tagged template literals, where a function gets to play around with the template literal.
Using template literals:
- Standard Templates:
let summary = \Total: ${total}`;` - Tagged Templates:
Regular expressions: Anchors away!
In regular expressions, the $ sign is like a grumpy sentinel that only matches at the end of a line or string, which is very handy in pattern matching and string validation.
Regular expression examples:
- To match line ending with 'end':
/end$/ - Ensure proper currency format:
/^\$[0-9]+(\.[0-9]{2})?$/
Scenarios and best practices around $
Clarity through consistent naming
When naming variables, you can use $ prefix as a naming convention. For example, consistent usage of $ to prefix all jQuery-related variables can make them stand out in your code.
Resolving conflicts in jQuery
In jQuery, $ can clash with other libraries using the same symbol. jQuery provides noConflict() function to return control of $ to any other library that loaded first.
Resolving conflicts with noConflict():
Safety with private fields
While $ has traditionally been used to denote 'special' or meta-information variables, newer proposals for private class fields offer syntax-level privacy using # instead. But $ could still serve as a marker for package-level or 'special' variables.
Why # for private fields?
- Ensures syntax-level privacy.
- Avoids naming collisions in class hierarchy.
Was this article helpful?