2

What is a difference between these two variables? (please see dollar sign)

var $button = $("<input>");

and

var button = $("<input>");

?

jnemecz
  • 3,171
  • 8
  • 41
  • 77
  • 1
    There is none but by convention it is better to put a $ prefix to variable name referring a jq object, making code easier to read – A. Wolff Feb 20 '16 at 10:15
  • `$` is widely used to indicate jQuery, and these days Angular.. The same with `_` which is usually the underscore library (or a prefix to indicate `private` variables) it has no meaning in javascript, it serves purely to indicate what you as a programmer can expect the variable to contain. [For fun and anger, variable name validator](https://mothereff.in/js-variables). – Rogier Spieker Feb 20 '16 at 10:26

2 Answers2

2

It just a developer taste. Suppose you want to save a HTML element in a variable in your program you do this.

var $input = $('input');

So when ever we see the variable $input we are sure that this hold a jQuery object (the html element on which jquery library functions can be performed on eg: $input.toggle(), $input.remove(), $input.val() etc).

where the normal variable name without $ are to point out program variables. For Example we can say variables which holds some values that cant perform math operations. like

var shippingCost = 40;
var quantity = $('#totalQuantity').val();
  var totalCost = $('#totalCost').val();
  var finalPrice = (totalCost * quantity )+ shippingCost;

So you see here we do more of a math operations.

Also the usage of $ in variable names is purely the developers interest it all bubbles up to the code readability. Its just one of the Jquery Beast Coding Practices.

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
1

There is no real difference between these two variables. It's just a convention to start the names of variables which contain jQuery objects with a dollar sign. This makes it easier to distingiush them from variables containing HTML elements, for example.

Nik Hille
  • 48
  • 4