It may be a silly question but I haven't been able to find any documentations on this on the internet.
When declaring variables to use within Javascript i normally use var x = 0
but I've seen in jQuery tutorials that they use $x = 0
. What is the difference of those two ?
Also, would i call those two variables the same way or do i need to use the $ mark before ? So for example : for(i=0; i < x; i++)
or for(i=0; i < $x; i++)
In the following examples, it can be seen that we have used the values stored in JavaScript Variables are used inside the jQuery Selectors. Example 1: The concatenation technique can be applied in order to use the values stored in JavaScript variables.
In JavaScript, we can declare a variable in different ways by using different keywords. Each keyword holds some specific reason or feature in JavaScript. Basically we can declare variables in three different ways by using var, let and const keyword. Each keyword is used in some specific conditions.
Your var x = 0;
is fine. The only reason people sometimes use a $
with jQuery-specific variables is that it helps them remember that the variable contains the result of a call to the $()
function in jQuery. The $
is actually part of the variable name, so you would use $
everywhere you referred to the variable.
So this:
var x = $(".foo"); // Find all elements with class "foo" x.css("color", "blue"); // Make them all blue
Is exactly the same as this:
var $x = $(".foo"); // Find all elements with class "foo" $x.css("color", "blue"); // Make them all blue
They've just put a $
at the beginning of the name.
Note: You've quoted your "jQuery" example as simply $x = 0;
(without var
). Be sure you always declare your variables (using var
); otherwise, you're falling prey to the Horror of Implicit Globals.
The dollar sign $
is not a special character in JavaScript. It is a legal character in variable naming. Here's what constitutes a legal identifier in JavaScript:
A JavaScript identifier 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).
Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the \uXXXX Unicode escape sequences as characters in identifiers.
Some examples of legal names are
Number_hits
,temp99
, and_name
.
Some jQuery programmers (myself included) use the $
as a prefix on variable names to indicate that those variables refer to jQuery objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With