I have initialized 2 variables, var1
and $var2
under $(document).ready(function()
in jQuery. What is the main difference (or the possible differences) between these 2 variables?
var1 = "var1";
$var2 = "var2";
$('#click1').click(function() {
alert(var1);
});
$('#click2').click(function() {
alert($var2);
});
Here is the working fiddle.
I have initialized 2 variables, var1
and $var2
under $(document).ready(function()
in jQuery. What is the main difference (or the possible differences) between these 2 variables?
var1 = "var1";
$var2 = "var2";
$('#click1').click(function() {
alert(var1);
});
$('#click2').click(function() {
alert($var2);
});
Here is the working fiddle.
Share Improve this question asked Mar 16, 2013 at 3:21 AlfredAlfred 21.4k63 gold badges174 silver badges257 bronze badges 4 |3 Answers
Reset to default 18There is no difference. Javascript allows the $
character in identifiers, such as variable and function names, just as it allows letters, digits, and certain other punctuation characters to be used. It has no special meaning.
jQuery sets the global $
variable to an object with a number of special behaviors, so variables beginning with $
are often reserved for variables or values related to jQuery. This is not enforced at any level, though. You're free to use $
in variable names wherever and however you like.
Actually they are the same. The "$" sign is used to indicate that the variable is used with jQuery. This is the convenient way for developer to note it. You can use both "var1" and "$var2" in pure javascript and jquery.
You should consider the rules to declare variable in JavaScript, you will see that you can use the "$" sign in your variable.
I don't think there are any difference between the two variables' scope. It's just that $var2 has a '$' sign in its variable name, and holds a different string value.
I found this thread to explain JavaScript scope quite well.
$
as a prefix for a variable name is to indicate this variable contains a jQuery object. As such using the$
Hungarian notation for variables which do not hold jQuery objects will cause tons of confusion. As stated already, using$
for none jQuery object variables is perfectly fine just be aware of the common understanding of variable names among your fellow developers working on the same project and how they might perceive the code. – Nope Commented Mar 16, 2013 at 3:41