Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery variable, what is the proper way to use a var?

I am sorry if this is a dumb or easy question but I am fairly new to Javascript/jQuery. The past month I have really started to delve into the land of scripting and have seen two different, maybe three, ways people use var in Javascript/jQuery.

The way I use a var is like so,

var nav = $('nav');

nav.hide();

A very common way I have seen people use vars,

var nav = $('nav');

$(nav).hide();

From the answers,

var $nav = $('nav');

$nav.hide();

From what I have learned from searching through Google is what you typed inside the variable is saved there to later be used. I then figured if I wrote the $() around the var when I was using it, it would duplicate the $(). Yet both ways seem to work so I know it does not duplicate it and therefore can tell that it is the same thing.

Is there a correct way to use vars or are both equally the same and it doesn't matter?

I apologize again if this is a known answer and will be happy to remove it if someone can show me the original question but I couldn't find anything on it.

A great bit of information from an answer that I didn't mark as the answer but I find to be very important.

var element = document.createElement("div");
$("body").append(element);
$(element).hide(); 

In the example above, $(element) is necessary, because it takes a DOM object and converts it to a jQuery selector. jQuery functions only work on jQuery selectors, so you couldn't simply do element.hide().

like image 343
Josh Powell Avatar asked Nov 30 '22 12:11

Josh Powell


1 Answers

$() creates a new jQuery object. If you save a jQuery object to a variable it is pointless to create another jQuery object from it, although it still works. You will often see people wrap variables that were previously created as jQuery objects in $() purely due to bad practice and either forgetting it's already an object...or not understanding what they just created in the first place

Perhaps you may have seen

var $nav = $('nav');

$nav.hide();

Using the $ prefix is a common practice to denote that the variable is a jQuery object for code readability mostly

like image 63
charlietfl Avatar answered Dec 10 '22 17:12

charlietfl