What's the difference between:
var add = "Hello";
and
$add = "Hello";
Could you tell me the difference between the two solutions without saying that one of them does not require jQuery ?
Thanks.
What's the difference between:
var add = "Hello";
and
$add = "Hello";
Could you tell me the difference between the two solutions without saying that one of them does not require jQuery ?
Thanks.
The first creates a scoped variable--one that's only available inside its parent function.
The second creates a global variable and is not a jQuery object, despite the dollar sign.
Naming a variable with a dollar sign is pure JavaScript and doesn't require JQuery. This may be a naming convention (see Why would a JavaScript variable start with a dollar sign?). Omitting 'var' makes the variable global and changes the scope of the variable.
The var keyword in front of a variable will basically declare that variable within the current scope. But, if that var keyword is missing, Javascript will search up the scope chain to see if there is a variable with that name in a different scope. And, since it finds a variable with the same name – testVar – in the global scope, Javascript will use that variable instead of declaring a new one local to the function.
$var is the name of the variable nothing more, so the proper way would be var $var;