what does the function name starts with '$' mean? [duplicate] - javascript

This question already has answers here:
What is the purpose of the dollar sign in JavaScript?
(12 answers)
Closed 2 years ago.
I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?
(I'm not asking about $('p.foo') syntax that you see in jQuery and others, but normal variables like $name and $order)

Very common use in jQuery is to distinguish jQuery objects stored in variables from other variables.
For example, I would define:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
I find this to be very helpful in writing jQuery code and makes it easy to see jQuery objects which have a different set of properties.

In the 1st, 2nd, and 3rd Edition of ECMAScript, using $-prefixed variable names was explicitly discouraged by the spec except in the context of autogenerated code:
The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.
However, in the next version (the 5th Edition, which is current), this restriction was dropped, and the above passage replaced with
The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.
As such, the $ sign may now be used freely in variable names. Certain frameworks and libraries have their own conventions on the meaning of the symbol, noted in other answers here.

As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).
In short you can use the $ whenever you want. (The interpreter won't complain.) The question is when do you want to use it?
I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.
For example:
var $get = function(id) { return document.getElementById(id); }
That seems like a reasonable convention.

I was the person who originated this convention back in 2006 and promoted it on the early jQuery mailing list, so let me share some of the history and motivation around it.
The accepted answer gives this example:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
But that doesn't really illustrate it well. Even without the $, we would still have two different variable names here, email and email_field. That's plenty good right there. Why would we need to throw a $ into one of the names when we already have two different names?
Actually, I wouldn't have used email_field here for two reasons: names_with_underscores are not idiomatic JavaScript, and field doesn't really make sense for a DOM element. But I did follow the same idea.
I tried a few different things, among them something very similar to the example:
var email = $("#email"), emailElement = $("#email")[0];
// Now email is a jQuery object and emailElement is the first/only DOM element in it
(Of course a jQuery object can have more than one DOM element, but the code I was working on had a lot of id selectors, so in those cases there was a 1:1 correspondence.)
I had another case where a function received a DOM element as a parameter and also needed a jQuery object for it:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var emailJQ = $(email);
// Now email is the DOM element and emailJQ is a jQuery object for it
}
Well that's a little confusing! In one of my bits of code, email is the jQuery object and emailElement is the DOM element, but in the other, email is the DOM element and emailJQ is the jQuery object.
There was no consistency and I kept mixing them up. Plus it was a bit of a nuisance to keep having to make up two different names for the same thing: one for the jQuery object and another for the matching DOM element. Besides email, emailElement, and emailJQ, I kept trying other variations too.
Then I noticed a common pattern:
var email = $("#email");
var emailJQ = $(email);
Since JavaScript treats $ as simply another letter for names, and since I always got a jQuery object back from a $(whatever) call, the pattern finally dawned on me. I could take a $(...) call and just remove some characters, and it would come up with a pretty nice name:
$("#email")
$(email)
Strikeout isn't perfect, but you may get the idea: with some characters deleted, both of those lines end up looking like:
$email
That's when I realized I didn't need to make up a convention like emailElement or emailJQ. There was already a nice convention staring at me: take some characters out of a $(whatever) call and it turns into $whatever.
var $email = $("#email"), email = $email[0];
// $email is the jQuery object and email is the DOM object
and:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var $email = $(email);
// $email is the jQuery object and email is the DOM object
// Same names as in the code above. Yay!
}
So I didn't have to make up two different names all the time but could just use the same name with or without a $ prefix. And the $ prefix was a nice reminder that I was dealing with a jQuery object:
$('#email').click( ... );
or:
var $email = $('#email');
// Maybe do some other stuff with $email here
$email.click( ... );

In the context of AngularJS, the $ prefix is used only for identifiers in the framework's code. Users of the framework are instructed not to use it in their own identifiers:
Angular Namespaces $ and $$
To prevent accidental name collisions with your code, Angular prefixes names of public objects with $ and names of private objects with $$. Please do not use the $ or $$ prefix in your code.
Source: https://docs.angularjs.org/api

Stevo is right, the meaning and usage of the dollar script sign (in Javascript and the jQuery platform, but not in PHP) is completely semantic. $ is a character that can be used as part of an identifier name. In addition, the dollar sign is perhaps not the most "weird" thing you can encounter in Javascript. Here are some examples of valid identifier names:
var _ = function() { alert("hello from _"); }
var \u0024 = function() { alert("hello from $ defined as u0024"); }
var Ø = function() { alert("hello from Ø"); }
var $$$$$ = function() { alert("hello from $$$$$"); }
All of the examples above will work.
Try them.

The $ character has no special meaning to the JavaScript engine. It's just another valid character in a variable name like a-z, A-Z, _, 0-9, etc...

Since _ at the beginning of a variable name is often used to indicate a private variable (or at least one intended to remain private), I find $ convenient for adding in front of my own brief aliases to generic code libraries.
For example, when using jQuery, I prefer to use the variable $J (instead of just $) and use $P when using php.js, etc.
The prefix makes it visually distinct from other variables such as my own static variables, cluing me into the fact that the code is part of some library or other, and is less likely to conflict or confuse others once they know the convention.
It also doesn't clutter the code (or require extra typing) as does a fully specified name repeated for each library call.
I like to think of it as being similar to what modifier keys do for expanding the possibilities of single keys.
But this is just my own convention.

${varname} is just a naming convention jQuery developers use to distinguish variables that are holding jQuery elements.
Plain {varname} is used to store general stuffs like texts and strings.
${varname} holds elements returned from jQuery.
You can use plain {varname} to store jQuery elements as well, but as I said in the beginning this distinguishes it from the plain variables and makes it much easier to understand (imagine confusing it for a plain variable and searching all over to understand what it holds).
For example :
var $blah = $(this).parents('.blahblah');
Here, blah is storing a returned jQuery element.
So, when someone else see the $blah in the code, they'll understand it's not just a string or a number, it's a jQuery element.

As I have experienced for the last 4 years, it will allow some one to easily identify whether the variable pointing a value/object or a jQuery wrapped DOM element
Ex:
var name = 'jQuery';
var lib = {name:'jQuery',version:1.6};
var $dataDiv = $('#myDataDiv');
in the above example when I see the variable "$dataDiv" i can easily say that this variable pointing to a jQuery wrapped DOM element (in this case it is div). and also I can call all the jQuery methods with out wrapping the object again like $dataDiv.append(), $dataDiv.html(), $dataDiv.find() instead of $($dataDiv).append().
Hope it may helped.
so finally want to say that it will be a good practice to follow this but not mandatory.

While you can simply use it to prefix your identifiers, it's supposed to be used for generated code, such as replacement tokens in a template, for example.

Angular uses is for properties generated by the framework. Guess, they are going by the (now defunct) hint provided by the ECMA-262 3.0.

$ is used to DISTINGUISH between common variables and jquery variables in case of normal variables.
let you place a order in FLIPKART then if the order is a variable showing you the string output then it is named simple as "order" but if we click on place order then an object is returned that object will be denoted by $ as "$order" so that the programmer may able to snip out the javascript variables and jquery variables in the entire code.

If you see the dollar sign ($) or double dollar sign ($$), and are curious as to what this means in the Prototype framework, here is your answer:
$$('div');
// -> all DIVs in the document. Same as document.getElementsByTagName('div')!
$$('#contents');
// -> same as $('contents'), only it returns an array anyway (even though IDs must be unique within a document).
$$('li.faux');
// -> all LI elements with class 'faux'
Source:
http://www.prototypejs.org/api/utility/dollar-dollar

The reason I sometimes use php name-conventions with javascript variables:
When doing input validation, I want to run the exact same algorithms both client-side,
and server-side. I really want the two side of code to look as similar as possible, to simplify maintenance. Using dollar signs in variable names makes this easier.
(Also, some judicious helper functions help make the code look similar, e.g. wrapping input-value-lookups, non-OO versions of strlen,substr, etc. It still requires some manual tweaking though.)

A valid JavaScript identifier shuold must start with a letter,
underscore (_), or dollar sign ($);
subsequent characters can also
be digits (0-9). Because JavaScript is case sensitive,
letters
include the characters "A" through "Z" (uppercase) and the
characters "a" through "z" (lowercase).
Details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables

Related

What is $this here in this JavaScript?

I'm looking at JavaScript that produces:
The related code is
My question is, what does $this refer to? Just the keyword "this" I understand, but $this? There doesn't seem to be any jQuery around.
Thanks for any illumination.
It has to do with the Google "jstemplate" mechanism.
From that page:
$this: $this refers to the JsEvalContext data object used in processing the current node. So in the above example we could substitute $this.end for end without changing the meaning of the jscontent expression. This may not seem like a very useful thing to do in this case, but there are other cases in which $this is necessary. If the JsEvalContext contains a value such as a string or a number rather than an object with named properties, there is no way to retrieve the value using object-property notation, and so we need $this to access the value.
It appears to be prefixed with $ due to using the Google JSTemplate API.
More information here: http://code.google.com/p/google-jstemplate/wiki/HowToUseJsTemplate
That is not javascript, it’s HTML.
What you see is a custom element property called jsdisplay that has the value of $this.something. What it actually does is very hard to give an exact answer to, but as some other pointed out it’s probably used internally in google templating.
Pointy is right for this specific case.
To clear up the confusion about $ in JavaScript:
In JavaScript the dollar sign ($) in variable names is treated like a-z, A-Z and underscore (_).
The variable you are looking at, could have been named anything else. $this is no special JS keyword. The developers of jstemplate could have named it foo if they wanted to. Or like they did, something similar to this, like _this or self.

$ at the beginning and at the end of variable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why would a JavaScript variable start with a dollar sign?
I realized some syntax with jquery and didnt know what it is. here goes:
var $foo = $("bar").blah();
var hello$ = $("stgelse").etc();
What is the difference between these? and why are they like that?
Also, For example:
var $foo = $("").blah();
var should already contain whatever right side is returning ? no?
Can you please elaborate?
In Javascript you can use $ in a variable name (or as a variable name all by itself, like it's used by the jQuery library for example), there is no special meaning in the language itself.
Some people use $ at the beginning of a variable name to indicate that the variable should contain a jQuery object, for example:
var $form = $('form');
A $ at the end of variable names was used in BASIC for string variables, which might be one reason for using it to mean something when naming variables in other languages also. Example:
10 LET NAME$="JOHN DOE"
20 PRINT NAME$
var $foo = $("bar").blah();
var is a keyword that makes the variable local in certain cases. See this question
$foo is the name of this variable. There is no need for the $, and indeed it confuses everything, but some languages (like PHP) need them to say "this is a variable". It could've been just foo
= is the assignment to make $foo have whatever comes from the right hand side
$ is another variable, but a special one: this is your JQuery thingy! From there you see it does all the JQuery stuff, like "find bar, do blah() etc.
The same basically goes for the other line, but in this case someone thought that hello$ would be a nice name for a var :)
here
var hello$ and $foo
hello$ , $foo are just a variable name
and $("").blah();
$ is jquery object
$ is just a name - names in JavaScript can contain dollar signs, and can consist of just a dollar sign.
Its like just normal javascript variable but as per convention is used to identify jquery objects variable from normal javascript variable. there nothing special about it.

JavaScript Double Dollar Sign

I understand the use of the (single) dollar sign in popular JavaScript libraries such as jQuery and Prototype. I also understand the significance of the double dollar sign in PHP (variable variables). Dean Edwards uses the double dollar sign in his famous addEvent() JavaScript function. Here is an except containing the use of the double dollar sign:
function addEvent(element, type, handler) {
// assign each event handler a unique ID
if (!handler.$$guid) handler.$$guid = addEvent.guid++;
// create a hash table of event types for the element
if (!element.events) element.events = {};
// create a hash table of event handlers for each element/event pair
var handlers = element.events[type];
if (!handlers) {
handlers = element.events[type] = {};
// store the existing event handler (if there is one)
if (element["on" + type]) {
handlers[0] = element["on" + type];
}
}
// store the event handler in the hash table
handlers[handler.$$guid] = handler;
// assign a global event handler to do all the work
element["on" + type] = handleEvent;
};
// a counter used to create unique IDs
addEvent.guid = 1;
From what I've read, the dollar sign only officially has significance in JavaScript for code generation tools, although that standard is largely ignored today due to the dollar signs widespread usage in the aforementioned JavaScript libraries.
Can anyone shed any light on this usage of the double dollar sign in JavaScript?
Thanks very much!
I wrote this function. :)
There is no longer any special significance to the $$ prefixes. It was a notation that I used back when packer was popular. Packer would shorten variable names with this prefix. Nowadays Packer will automatically shorten variable names so this notation is redundant.
Short answer, the $ sign is a valid identifier in JavaScript so you are just looking at a bunch of ugly variable names. ;)
Well really, it's just the naming convention of the developer. "$$" might as well as be "aa", for all intents and purposes.
As you mentioned, the single dollar sign function $() has become almost-standard in various JavaScript libraries. "The one function to rule them all", eh? But remember, it's nothing inherent to JS itself. It's just a function name that caught on to replace document.getElementById().
So, with that said, $$ could be anything. Heck, you could even have a function like this:
function $$$$$$$$(){
//i've got dollar signs in my eyes!
}
In other words, it's just a variable/function name—just like all the rest.
Just as others have said, $$ is an arbitrary identifier.
The JavaScript toolkit MochiKit reserves a function identified by the same to select elements using CSS selector syntax, much like jQuery does, except without wrapping all the matching elements in a special object.
So, yeah - it's nothing particularly special, in and of itself.
As far as I know, the dollar sign is just a regular character that can be used in variable names. It could be a convention to signify a property that shouldn't be messed around with.
My guess is that the author used $$guid to avoid clashing with existing property names. He could probably have used __guid or something similar instead.
Double dollar sign is referenced in the following terms -
//getElementById
function $$(id){
return document.getElementById(id);
}

What is the meaning of "$" sign in JavaScript

In the following JavaScript code there is a dollar ($) sign. What does it mean?
$(window).bind('load', function() {
$('img.protect').protectImage();
});
Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).
There's nothing mysterious about the use of $ in JavaScript. $ is simply a valid JavaScript identifier. JavaScript allows upper- and lower-case letters (in a wide variety of scripts, not just English), numbers (but not at the first character), $, _, and others.¹
Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it. In that case you use jQuery instead of $. In fact, $ is just a shortcut for jQuery.
¹ For the first character of an identifier, JavaScript allows "...any Unicode code point with the Unicode property “ID_Start”..." plus $ and _; details in the specification. For subsequent characters in an identifier, it allows anything with ID_Continue (which includes _) and $ (and a couple of control characters for historical compatibility).
From another answer:
A little history
Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:
var $ = document.getElementById; //freedom from document.getElementById!
When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.
jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $ represents the jQuery Function, and is actually a shorthand alias for jQuery. (Unlike in most languages, the $ symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
The $() is the shorthand version of jQuery() used in the jQuery Library.
In addition to the above answers, $ has no special meaning in javascript,it is free to be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, you may encounter situations where you want to use it in conjunction with another JS library that also uses $, which would result a naming conflict. There is a method in JQuery just for this reason, jQuery.noConflict().
Here is a sample from jQuery doc's:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
Alternatively, you can also use a like this
(function ($) {
// Code in which we know exactly what the meaning of $ is
} (jQuery));
Ref:https://api.jquery.com/jquery.noconflict/
From the jQuery documentation describing the jQuery Core Object:
Many developers prefix a $ to the name of variables that contain jQuery
objects in order to help differentiate. There is nothing magic about
this practice – it just helps some people keep track of what different
variables contain.
Basic syntax is: $(selector).action()
A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)

Why would a JavaScript variable start with a dollar sign? [duplicate]

This question already has answers here:
What is the purpose of the dollar sign in JavaScript?
(12 answers)
Closed 2 years ago.
I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?
(I'm not asking about $('p.foo') syntax that you see in jQuery and others, but normal variables like $name and $order)
Very common use in jQuery is to distinguish jQuery objects stored in variables from other variables.
For example, I would define:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
I find this to be very helpful in writing jQuery code and makes it easy to see jQuery objects which have a different set of properties.
In the 1st, 2nd, and 3rd Edition of ECMAScript, using $-prefixed variable names was explicitly discouraged by the spec except in the context of autogenerated code:
The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.
However, in the next version (the 5th Edition, which is current), this restriction was dropped, and the above passage replaced with
The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.
As such, the $ sign may now be used freely in variable names. Certain frameworks and libraries have their own conventions on the meaning of the symbol, noted in other answers here.
As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).
In short you can use the $ whenever you want. (The interpreter won't complain.) The question is when do you want to use it?
I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.
For example:
var $get = function(id) { return document.getElementById(id); }
That seems like a reasonable convention.
I was the person who originated this convention back in 2006 and promoted it on the early jQuery mailing list, so let me share some of the history and motivation around it.
The accepted answer gives this example:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
But that doesn't really illustrate it well. Even without the $, we would still have two different variable names here, email and email_field. That's plenty good right there. Why would we need to throw a $ into one of the names when we already have two different names?
Actually, I wouldn't have used email_field here for two reasons: names_with_underscores are not idiomatic JavaScript, and field doesn't really make sense for a DOM element. But I did follow the same idea.
I tried a few different things, among them something very similar to the example:
var email = $("#email"), emailElement = $("#email")[0];
// Now email is a jQuery object and emailElement is the first/only DOM element in it
(Of course a jQuery object can have more than one DOM element, but the code I was working on had a lot of id selectors, so in those cases there was a 1:1 correspondence.)
I had another case where a function received a DOM element as a parameter and also needed a jQuery object for it:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var emailJQ = $(email);
// Now email is the DOM element and emailJQ is a jQuery object for it
}
Well that's a little confusing! In one of my bits of code, email is the jQuery object and emailElement is the DOM element, but in the other, email is the DOM element and emailJQ is the jQuery object.
There was no consistency and I kept mixing them up. Plus it was a bit of a nuisance to keep having to make up two different names for the same thing: one for the jQuery object and another for the matching DOM element. Besides email, emailElement, and emailJQ, I kept trying other variations too.
Then I noticed a common pattern:
var email = $("#email");
var emailJQ = $(email);
Since JavaScript treats $ as simply another letter for names, and since I always got a jQuery object back from a $(whatever) call, the pattern finally dawned on me. I could take a $(...) call and just remove some characters, and it would come up with a pretty nice name:
$("#email")
$(email)
Strikeout isn't perfect, but you may get the idea: with some characters deleted, both of those lines end up looking like:
$email
That's when I realized I didn't need to make up a convention like emailElement or emailJQ. There was already a nice convention staring at me: take some characters out of a $(whatever) call and it turns into $whatever.
var $email = $("#email"), email = $email[0];
// $email is the jQuery object and email is the DOM object
and:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var $email = $(email);
// $email is the jQuery object and email is the DOM object
// Same names as in the code above. Yay!
}
So I didn't have to make up two different names all the time but could just use the same name with or without a $ prefix. And the $ prefix was a nice reminder that I was dealing with a jQuery object:
$('#email').click( ... );
or:
var $email = $('#email');
// Maybe do some other stuff with $email here
$email.click( ... );
In the context of AngularJS, the $ prefix is used only for identifiers in the framework's code. Users of the framework are instructed not to use it in their own identifiers:
Angular Namespaces $ and $$
To prevent accidental name collisions with your code, Angular prefixes names of public objects with $ and names of private objects with $$. Please do not use the $ or $$ prefix in your code.
Source: https://docs.angularjs.org/api
Stevo is right, the meaning and usage of the dollar script sign (in Javascript and the jQuery platform, but not in PHP) is completely semantic. $ is a character that can be used as part of an identifier name. In addition, the dollar sign is perhaps not the most "weird" thing you can encounter in Javascript. Here are some examples of valid identifier names:
var _ = function() { alert("hello from _"); }
var \u0024 = function() { alert("hello from $ defined as u0024"); }
var Ø = function() { alert("hello from Ø"); }
var $$$$$ = function() { alert("hello from $$$$$"); }
All of the examples above will work.
Try them.
The $ character has no special meaning to the JavaScript engine. It's just another valid character in a variable name like a-z, A-Z, _, 0-9, etc...
Since _ at the beginning of a variable name is often used to indicate a private variable (or at least one intended to remain private), I find $ convenient for adding in front of my own brief aliases to generic code libraries.
For example, when using jQuery, I prefer to use the variable $J (instead of just $) and use $P when using php.js, etc.
The prefix makes it visually distinct from other variables such as my own static variables, cluing me into the fact that the code is part of some library or other, and is less likely to conflict or confuse others once they know the convention.
It also doesn't clutter the code (or require extra typing) as does a fully specified name repeated for each library call.
I like to think of it as being similar to what modifier keys do for expanding the possibilities of single keys.
But this is just my own convention.
${varname} is just a naming convention jQuery developers use to distinguish variables that are holding jQuery elements.
Plain {varname} is used to store general stuffs like texts and strings.
${varname} holds elements returned from jQuery.
You can use plain {varname} to store jQuery elements as well, but as I said in the beginning this distinguishes it from the plain variables and makes it much easier to understand (imagine confusing it for a plain variable and searching all over to understand what it holds).
For example :
var $blah = $(this).parents('.blahblah');
Here, blah is storing a returned jQuery element.
So, when someone else see the $blah in the code, they'll understand it's not just a string or a number, it's a jQuery element.
As I have experienced for the last 4 years, it will allow some one to easily identify whether the variable pointing a value/object or a jQuery wrapped DOM element
Ex:
var name = 'jQuery';
var lib = {name:'jQuery',version:1.6};
var $dataDiv = $('#myDataDiv');
in the above example when I see the variable "$dataDiv" i can easily say that this variable pointing to a jQuery wrapped DOM element (in this case it is div). and also I can call all the jQuery methods with out wrapping the object again like $dataDiv.append(), $dataDiv.html(), $dataDiv.find() instead of $($dataDiv).append().
Hope it may helped.
so finally want to say that it will be a good practice to follow this but not mandatory.
While you can simply use it to prefix your identifiers, it's supposed to be used for generated code, such as replacement tokens in a template, for example.
Angular uses is for properties generated by the framework. Guess, they are going by the (now defunct) hint provided by the ECMA-262 3.0.
$ is used to DISTINGUISH between common variables and jquery variables in case of normal variables.
let you place a order in FLIPKART then if the order is a variable showing you the string output then it is named simple as "order" but if we click on place order then an object is returned that object will be denoted by $ as "$order" so that the programmer may able to snip out the javascript variables and jquery variables in the entire code.
If you see the dollar sign ($) or double dollar sign ($$), and are curious as to what this means in the Prototype framework, here is your answer:
$$('div');
// -> all DIVs in the document. Same as document.getElementsByTagName('div')!
$$('#contents');
// -> same as $('contents'), only it returns an array anyway (even though IDs must be unique within a document).
$$('li.faux');
// -> all LI elements with class 'faux'
Source:
http://www.prototypejs.org/api/utility/dollar-dollar
The reason I sometimes use php name-conventions with javascript variables:
When doing input validation, I want to run the exact same algorithms both client-side,
and server-side. I really want the two side of code to look as similar as possible, to simplify maintenance. Using dollar signs in variable names makes this easier.
(Also, some judicious helper functions help make the code look similar, e.g. wrapping input-value-lookups, non-OO versions of strlen,substr, etc. It still requires some manual tweaking though.)
A valid JavaScript identifier shuold must start with a letter,
underscore (_), or dollar sign ($);
subsequent characters can also
be digits (0-9). Because JavaScript is case sensitive,
letters
include the characters "A" through "Z" (uppercase) and the
characters "a" through "z" (lowercase).
Details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables

Categories

Resources