What is the difference between var a and var $a in javascript?


Good afternoon!

More and more often in js scripts I encounter variable declarations using the dollar sign, i.e. instead of a simple declaration var A I see var $A, and in the further code for accessing this variable, then so $A, then so $(A) . Here, for example, is a piece from the script:

var forms = function(){
    $('.js_form').each(function(){ 
        var $form = $(this),
            $customField = $form.find('[data-error]'),
            customFieldRulls = {};
        var zIndexs = function(){
            setTimeout(function(){
                $('label.error').each(function(i){
                    $(this).css({'z-index':'50'-i})
                });                     
            },200)
        };

Both regular variables and "dollar variables" are used. I don't know what the difference is between them. It's just for convenience is it being done, or does it provide something additional from a functional point of view?

Author: Виталина, 2014-11-17

2 answers

I can't be sure for all 146%, but there is a feeling that the dollar icon here marks the fact that the variable value is obtained using the jQuery selector. While other, ordinary js variables go without this prefix. In principle, it looks quite logical - js is a language with dynamic typing, and it is not always possible to understand by the name of a variable what is stored in it. Therefore, the dollar prefix makes this easier to understand.

However, regardless of whether it is true whether my guess is correct or not, the ad "with a dollar" does not carry any new functionality - in js, this is the same symbol that can be used in the names of identifiers as the other

 11
Author: DreamChild, 2014-11-17 14:02:53

Not really. Based on the latest jQuery specifications:

<div id="selector"></div>
function ready() {
  var selector = $('#selector');
  var selector = $('#selector').context;
  var $selector = $('#selector');
}
window.onload = ready;

In the first case, selector returns [object Object]

In the second [object HTMLDocument] (so, for completeness)

And in the third [object HTMLDivElement]

In short, the third option will work as document.getElementById ('selector '); on pure JS.

And then you can see for yourself who needs to work with what and how.

 0
Author: Антон К., 2017-12-27 23:14:08