Tuesday, May 1, 2012

Declaring variables jQuery and JS


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++)


Source: Tips4all

3 comments:

  1. 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.

    ReplyDelete
  2. 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.

    See also


    Why prepend a $ to variable name.
    Jquery: The $ dollarsign
    Valid Characters for JavaScript Variable Names

    ReplyDelete
  3. No difference. The $ is just another character in JavaScript.

    It just happens that jQuery users use it to signify a variable that is referencing a jQuery object. There's no requirement though.

    ReplyDelete