Explain Codes LogoExplain Codes Logo

Why would a JavaScript variable start with a dollar sign?

javascript
jquery
coding-guidelines
best-practices
Anton ShumikhinbyAnton Shumikhin·Aug 7, 2024
TLDR

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:

let $veritablePlanet = $('#our-planet'); //jQuery picked the earth from a universe of DOM elements

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:
let $broccoli = $(".healthy-veg"); //Spinach lost the vote!
  • During certain library interactions, the $ token plays shortcut or alias for library functions or utilities:
let $ = lodash; // Lodash's $ quarter: Shorter, but covers the whole yard!

Prefixing as signboards for easy readability

  • Signposting jQuery-retrieved elements:
let $vine = $('#grapes'); // Only if Jack's beanstalk was this easy to select!
  • With AngularJS, signalling services or core AngularJS objects:
angular.module('myLunch').controller('LunchMenu', function($scope, $http){ // $scope and $http are AngularJS-infused services, not lunch items! });
  • Used by discerning developers for highlighting variables with a unique stature in the script:
let $thanos = computeInfinityStones(); // Potential threat, handle with caution!

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.