Doubt in jQuery variable creation

Asked

Viewed 222 times

2

Researching materials on jQuery I noticed that some articles use two types of variable declaration, some using the dollar sign and others not, as in the example below:

Alternative 1

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

Alternative 2

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

Is there any difference between the two ways? When to use one or the other?

4 answers

3

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

so much Row how much $Row are normal variables.

The "difference" is in the readability of the code itself. There is a certain variable naming convention that will hold a Jquery object, where these are initiated by dollar ($).

Example:

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

I hope I’ve helped.

2

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

1


The general rules for the construction of names for the variables (unique identifiers) are:

  • Names may contain letters, numbers, underscores and dollar signs.
  • Names should start with a letter
  • Names can also start with $ and _
  • Names are upper case (y and y are different variables)
  • Reserved words (such as Javascript keywords) cannot be used as names

There is no difference between this and different variables.

Situation for use

  • Sometimes people when already working with PHP have a habit of declaring variables with $ forward to maintain some pattern, or psychological. I personally dislike.

  • In some cases when working with encapsulation or name-space can be defined which global variables should start with _ and internal variables with $, may vary to upper or lower case, but this is already standard design.

Concluding

Both are independent variables, in terms of nomenclature in javascript not the difference. There may be a case of working with some project pattern, but merely organizational and psychological.

1

the dollar sign ($) is an acronym for jQuery. Many people use it in variables only to represent that the elements worked belong to the jquery object, and not only to 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 such as mootools for example.

var jKelly = jQuery.noConflict();
jKelly( "div" ).text('Olá Kelly');
  • Thank you all, I understand better!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.