Why would a JavaScript variable start with a dollar sign?
The dollar sign $
prefixing a JavaScript variable doesn't signify a syntax requirement. Rather, it typically earmarks a jQuery object, implies cached or special values, or simply airs a stylistic choice programmers make.
Consider this robuster planet:
Birth of the dollar sign in JS
jQuery, one of the most popular JavaScript libraries, struck the convention of dollar sign prefixes in JavaScript variable names. This pattern is less about syntax and more about quickly distinguishing jQuery objects from traditional variables or native DOM elements.
In mixed scripts environment, a cursory glance at $xyzElement
vouches for it being a jQuery-wrapped object.
Framework factor & boundaries
Certain frameworks like AngularJS specifically dedicate the dollar prefix to public services and methods, while $$
is marked for internal/private parts of the framework. This allows developers to elegantly skirt around naming crashes, and precisely earmark their properties or functions.
Coding guidelines & etiquettes
Deploying the dollar prefix isn't hard-coded in JavaScript syntax, but is ordained as a coding best practice within specific JavaScript libraries. Adherence to such naming conventions like $
can resultantly escalate code readability and maintainability.
However, don't forget to match the pulse of your remaining codebase conventions or team’s coding standards to eschew confusion.
The right scene for the dollar sign
The jQuery and libraries' scene
- When wrestling with jQuery selections, conventionally, variables are dollar-prefixed to indicate their role as custody for jQuery objects:
- During certain library interactions, the
$
token plays shortcut or alias for library functions or utilities:
Prefixing as signboards for easy readability
- Signposting jQuery-retrieved elements:
- With AngularJS, signalling services or core AngularJS objects:
- Used by discerning developers for highlighting variables with a unique stature in the script:
Treading carefully
While using frameworks like AngularJS, avoid indulging in $
and $$
prefixed variable names as this risks colliding with the framework’s inherent services or features.
Was this article helpful?