Reading a javascript script, why so many $ (dollar signs)? - javascript

I am trying to decipher a .js script and I am finding it filled with $ throughout? Is there any reason to use this? I'm pretty new to JavaScript.

I think you are reading a JavaScript library famously known as jQuery (or possibly another library). The $ is just a short form for a namespace or use as an identifier.
You can think of it like this jQuery('p') to select all the paragraphs on a page,
or for short form you can just write $('p').
Here is a link for jQuery tutorials/docs jQuery
Here is a list of standards section 7.6 describes it in detail ECMA Standard

A number of libraries have used $ as their primary symbol. It's nothing to do with JavaScript per se, but it's a short distinctive symbol and so libraries have tended to glom onto it. (You can start an identifier with $ in JavaScript, and identifiers can be one character long, so $ is a valid identifier, just like a or x.)
I know of at least three libraries that use $ for something:
jQuery - It's the all purpose function for jQuery, an alias of the jQuery function; more here.
Prototype - It's Prototype's replacement for document.getElementById, more here. Prototype also has $$, which is for looking things up via CSS selectors.
MooTools - Same use as Prototype (because MooTools is either "inspired by" or "forked from" Prototype, some years back, depending on who you ask), more here. And like Prototype, it has $$.

$ is a variable. A number of frameworks use it as a short hand for using it. Prototype and Jquery are the two big ones. This does not mean that the $ automatically is either one of those. It could be anything as anything in JavaScript can assign something to the $. This is something to be aware of, because when you start combining scripts from different sources, it's really easy for one to accidentally reassign a variable to something else.
Most likely it is a framework reference, but you'll have to read the code to be sure. At one point in time the $ was meant to be used to indicate that the code referenced by it was auto generated, but this is just a guideline.

if you're new to javascript, $() can look strange.
Try to think of it like
var $ = function(){
//do something
}
So the dollar sign is just the name of a variable like any other.
var myFunction = function(){
//do something
}
// this is exactly the same just a different name.
So the dollar sign has no special meaning in javascript.
Frameworks like to use it because you are using their functions so often, having to write e.g. jQuery() every time would be tedious. Having one character is nice and short.
I think they also have a preference for the $ symbol, purely because it is unusual so it is quickly distinguishable from other code.
A quick way to find out if it is jQuery is to do console.log(jQuery) if the console returns a string of code $() is jQuery. If you get undefined, it is something else.

Maybe you're reading jQuery code.
Because JavaScript lets you define variables which start with $ sign, or literally which are only $. For example, you can do:
var $ = "something";
alert($);
jQuery is a library built on JavaScript (the most popular at the time) and it has a global object to keep everything encapsulated. You access that global object using $.

The script is probably using a third party library such as Prototypejs or jQuery or he defined his own function $() which explain why the dollar sign appears so often in that script.

It's a jQuery function. That's what it is most probably. Might also be the Prototype library, or just a function that does something that's needed many times in the code, like getElementById etc

Without seeing the code, it sounds like the script you are looking at makes use of jQuery, as the $ is the default jQuery object.

Typically the $ will represent jQuery or another specific library (Moo Tools, etc.) . $ is the shortened form of referencing the jQuery object (or whatever library it was assigned). It makes the code much more readable and easy to use.
If you are just learning javascript, you will soon become very familiar with jQuery. :)

Either its jQuery or an old PHP habit by some javascript programmer :)

$ is only a function. It means you work with some javascript superstructure (framework).

Related

Avoid $ conflict with jQuery

I am pretty sure this must have been asked in another form, but searching for the $ sign does not yield any results here.
I have already made a big system, and used jQuery extensively, referencing it with the $. At this point, I don't want to go back.
My problem is that now I have implemented CKEditor, which also references itself with the $, like many other JavaScript frameworks. So now I get a conflict and lots of:
Uncaught TypeError: cannot get property 'any_function' of undefined
I don't want to go through the CKEditor code, searching and replacing, since I will be updating in the future. I also want to keep using $ for jQuery, but nothing else.
Off course I cannot simply use:
$.noConflict()
Without breaking my scripts.
Is there a way where I can keep using $ for jQuery whenever I want, while letting my JavaScript frameworks use $ internally?
What is my best/easiest solution here?
You can wrap either sets of your code in an IIFE and pass the relevant object to it.
(function($) {
// Code that uses jQuery
})(jQuery);
I'd also suggest assigning CKEditor to something else right after it's been loaded so that you can follow a similar pattern for CKEditor code.
// Right after loading CKEditor
var CKEditor = $;
// Code that uses CKEditor
(function($) {
...
})(CKEditor);
Although it'd be more sustainable to just reassign CKEditor to another variable and only use that variable.

Which Javascript library other than jQuery uses $?

$ is not a function is a common error message newbies encounter when trying to use JQuery in Drupal 7.
The explanation is that the usage of $ is disabled in Drupal to avoid conflicts with other libraries. But which other library is using $?
At least two major ones:
PrototypeJS,
Mootools,
It is probably because using one char for most commonly used function saves a lot of time. And due to some restrictions for characters in variable name in JavaScript there are actually two candidates for such one-char names: $ and _ (_ is used often for eg. gettext functions or throw-away variables). Thus I would rather expect that if some framework has some shortcut function with one char name, it is probably $.
One of the common problems is several different versions of JQuery itself, though I'm not sure that is the reason in Drupal.
Another possibility is Mootools
zepto also uses $, and is a lightweight alternative to jQuery:
http://zeptojs.com/
In addition, it matches most of the jQuery API.

Mixing javascript and jquery within namespace

Was having trouble a few weeks ago getting jquery to run in firebug (esp on drupal sites). Apparently the issue was that Drupal was grabbing the $ variable, so I got a little namespace snippet (function($)...(Jquery)); that reclaimed the $. I have been using the namespace in firebug but geting inconsistent results, especially when mixing pure javascript and Jquery within the namespace. I understand that all Jquery is javascript and they work together, but looking at samples I see some weird variations in the way people deploy this namespace. As a general question but also specifically within Firebug context, is there any need to place javascript in any particular relation to namespaced Jquery (inside the namespace, function calls inside, function out, or any other convention)?
Thanks
If you meant preventing the $ from being reclaimed, there is no convention but there is a way. other frameworks also use the $ name. anything declared later to use $ will take over $. however, you can prevent it or get around it.
jQuery offers a lot of ways to prevent it via its noConflict() method. but my preferred method is just wrap them in a function. jQuery also uses the jQuery namespace. $ is a shorthand alias, a very common one too. so functions like $.each() is also jQuery.each(). what crazy framework uses jQuery as its namespace anyway?
an example of wrapping in a function is like this:
(function($){
//inside here, "$" is jQuery
}(jQuery)); //pass "jQuery"

Javascript function declarations with a dollar sign

This function declaration doesn't make sense to me. What does the $ sign do?
function $(id) { return document.getElementById(id); }
Also, this code is interfering with other Javascript code. If I comment it out, then the other Javascript code I'm trying to use works, but then I lose some other functionality.
Why might it be interfering with my other code.
What does the $ sign do?
Nothing special. It is just a character that can be used in variable/function names.
There has been a trend to use $ as the name to the gateway function for a number of libraries (including Mootools, Prototype and jQuery). This has two major problems:
It makes them conflict with each other
It violates the principles of self-documenting code
Also, this code is interfering with other Javascript code.
Presumably something else is using a variable called $ then.
You are declaring a function called $ that wraps document.getElementById, apparently for convenience. Nothing special.
Reference What characters are valid for JavaScript variable names?
As for the interference, there is likely another global variable called $, which is being clobbered. See jQuery.
JavaScript variables can start (and only consist of) a $ (amongst others).
Previously, the $ was added solely for machine generated variables.
This was in the spec I believe, but has since been removed (don't quote me).
Dollar sign was added to the language specifically for use by code
generators and macro processes, so if you have machines writing code
then the machines need to be confident that the variables that they
create will not conflict with variables that the humans are going to
create. To distinguish them, we’ll allow the machines to use dollar
sign. Some of the ninjas found out about that and thought oh, dollar
sign, I can use dollar sign as a function name, so they’re out there
doing that. And it looks stupid. I mean, look at a program with dollar
sign.
Source: Douglas Crockford.
If it is interfering with other code, you may be using a library which uses this identifier. If that's the case, look at the no conflict mode for that library (if it has one).
Let me guess: are you using jQuery or prototype?
$ and _ are valid characters in variable/function names. The code is the same as declaring function a(id) {return document.getElementById(id);}.
It's typically used as a shortcut for selecting an element because typing document.getElementById is much too long for how often it's used.

What is the $ symbol used for in JavaScript

I am a JavaScript learner and have been researching this matter, but with no success. What is the $ symbol used for in JavaScript besides regular expressions? Any resources or readings regarding this would be appreciated. Thanks.
It doesn't mean anything special.
But because $ is allowed in identifier names, many Javascript libraries have taken to using $ as the "central" interface to them, or at least as a shortcut for accessing their functionality.
For example, if you're using jQuery and you say $("div"), this is a call to the $ function with argument "div". When you say $.post(), it's calling the post method on the $ object (Javascript is nice in that functions are first-class objects).
I became acquainted with it in JavaScript when I started using the Prototype framework. In Prototype, $ is simply the name of an often used function (very, very much simplified - a short for document.getElementById). Personally, I like the terseness of it.
Afaik, it's not used for anything by the language itself.
For what it's worth, Douglas Crockford advises against using $ in the variable/function names you write:
Do not use $ (dollar sign) or \
(backslash) in names.
Adding another, rather opinionated, quote from Mr. Crockford's talk "And Then There Was JavaScript":
Dollar sign was added to the language
specifically for use by code
generators and macro processes, so if
you have machines writing code then
the machines need to be confident that
the variables that they create will
not conflict with variables that the
humans are going to create. To
distinguish them, we’ll allow the
machines to use dollar sign. Some of
the ninjas found out about that and
thought oh, dollar sign, I can use
dollar sign as a function name, so
they’re out there doing that. And it
looks stupid. I mean, look at a
program with dollar sign.
If you are asking why some variables and function names start with $, then that is simply a convention when using jQuery and/or AngularJS.
In code that uses jQuery, $ is often used as a prefix for variables that contain jQuery selections.
e.g. var $container = $('.container');.
In AngularJS, they use the $ prefix to mean "core Angular functionality". That way, you know which methods and services are added by the framework, and which are custom to your application.

Categories

Resources