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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With