4

What's the difference between following types of var declaration in JavaScript?

$x

var x

var $x

4 Answers 4

7

$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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

This answer may seem confusing given the current content of the question since there is no longer any tag or mention of jQuery. To elaborate, $x and x variable names are no more different than xy and x. However, $ is sometimes used at the beginning of variable names by convention to indicate that the variable stores a reference to a jQuery object.
3

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.