Doubt in jQuery variable creation

1

Looking at jQuery materials I noticed that some articles use two types of variable declarations, some using the dollar sign and some not, as in the example below:

Alternative 1

var $row =$("<tr/>")

Alternative 2

var row =$("<tr/>")

Is there a difference between the two forms? When to use one or the other?

    
asked by anonymous 19.10.2015 / 00:51

4 answers

1

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, numbers, underscores, and dollar signs.
  • Names should begin with a letter
  • Names can also start with $ e _
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (as JavaScript keywords) can not be used as names

From this situation there is no difference apart from being different variables.

Situation for use

  • Sometimes people who already work with PHP have the habit of declaring the variables with $ up front to maintain some pattern, or psychological. I personally do not like it.

  • In some cases when working with encapsulation or name-space you can define which global variables should start with _ and internal variables with $ , and may vary to uppercase or lowercase, but this is already design pattern.

Completing

Both are independent variables, in terms of nomenclature in javascript, not the difference. There may be cases if you are working with some design pattern, but merely organizational and psychological.

    
19.10.2015 / 13:30
3

Well, there's no difference between the two statements.

row and $ row are normal variables.

The "difference" lies in the readability of the code itself. There is a certain convention naming variables that will save a JQuery object, where these are initialized by dollar sign ($).

Example:

var input = document.createElement("input");
var $input = $("<input>");

I hope I have helped.

    
19.10.2015 / 01:46
2

The two forms work the same, it's a matter of convention that some programmers like to create variables with the dollar sign at the beginning to identify that the variable has some jquery code.

    
19.10.2015 / 01:43
1

The dollar sign ( $ ) is a jQuery acronym. Many people use it in variables just to represent that the elements worked belong to the jquery object, not just an attribute of the function or method, this is not a rule, but a way to organize the code.

This acronym is often replaced to avoid conflicts between codes like mootools for example.

var jKelly = jQuery.noConflict();
jKelly( "div" ).text('Olá Kelly');
    
19.10.2015 / 14:19