JavaScript variable declaration

What is the difference between the following var declaration types in JavaScript?

$x var x var $x 
+4
source share
4 answers

$ x and x are just two different variable names. Like var x and var y . Just using $ x is an implied declaration, except that if $ x exists in a higher scope, you will use it. The var $x declaration sets a new $ x in the current scope, which avoids conflicts with any other $ x in the higher scope.

+8
source

No difference except scope. $x is just a variable name, for example x . var creates the variables in the local scope, otherwise they are global.

This has nothing to do with jQuery.

+4
source

If you use $x without declaring it, you implicitly create a global variable called $x . var x and var $x each create a variable in any function (or global scope) you are in, called x and $x , respectively. None of them have anything to do with jQuery.

+3
source

Nothing. However, I consider it good practice to precede variable names with $ if it returns a jQuery object and without it, if it returns a DOM object or other type (string, etc.).

The term "var" is useful for defining an area. Always use "var" for the first declaration or at any time when you need the variable to be local in scope.

+1
source

Source: https://habr.com/ru/post/1343010/


All Articles