Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the official correct way to declare jQuery variables?

I am trying to learn jQuery. I keep seeing people using different methods of declaring variables.

I have seen var variable;, var $variable;, and $variable;. Which one (if any of these) is the official correct way to declare jQuery variables.

like image 963
chromedude Avatar asked Nov 24 '10 20:11

chromedude


2 Answers

You should always declare a variable with var (whatever the scope, unless creating it on an object), implied globals are bad, don't do it.

As for variable vs. $variable, there is no official stance, just have a convention that you and your team stick to.

As a general rule some follow, (I don't follow this, some do), use variable for variables that aren't jQuery objects and $variable for variables that are, those who use this typically find that seeing $something and knowing immediately it's a jQuery object to be handy.

like image 95
Nick Craver Avatar answered Nov 15 '22 16:11

Nick Craver


Use var to define variables to ensure that they are scoped properly, usually locally within a function. My convention is to use $variable when the variable holds a jQuery object (result of a selector) and variable for everything else.

BTW -- they aren't jquery variables, but rather javascript variables. JQuery is just another (albeit the most popular at present) javascript framework, not a language in and of itself.

like image 28
tvanfosson Avatar answered Nov 15 '22 17:11

tvanfosson