Reputation: 61
What's the difference between following types of var declaration in JavaScript?
$x
var x
var $x
Upvotes: 4
Views: 2292
Reputation: 26380
$x and x are simply two different variable names. Like var x
and var y
. Simply using $x is an implied declaration, except that if $x exists in a higher scope, you'll use it. declaring var $x
sets up a new $x in the current scope which avoids conflicts with any other $x at a higher scope.
Upvotes: 7
Reputation: 2700
If you use $x
without declaring it, you are implicitly creating a global variable called $x
. var x
and var $x
each create a variable in whatever function (or global scope) you're in, called x
and $x
, respectively. Neither has anything to do with jQuery.
Upvotes: 3
Reputation: 2576
Nothing. I find it good practice, however, to precede variable names with a $ if it returns a jQuery object and without if it returns a DOM object or other type (string, etc.)
The term 'var' is useful for determining scope. Always use 'var' on first declaration, or on anytime you need a variable to be local in scope.
Upvotes: 1
Reputation: 24344
No difference except for scope. $x
is just a variable name like x
. var
creates variables in a local scope, otherwise they are global.
This has nothing to do with jQuery, really.
Upvotes: 4