One my friends is saying $varName is used for caching and I was confused. Is this true?
The strongest convention I've seen for this is to indicate jQuery objects, but it's purely convention and not by any feature of the language. So there's a seed of truth in that people commonly use them to indicate it's a cached DOM reference; but it doesn't make it cached.
eg.
var $foo = $('expensiveDOMquery');
$foo.each(dothings);
$foo.each(domorethings);
Here $foo has been used twice but the DOM was only queried once.
I have actually seen this convention creep into vanilla JS projects as well, to indicate the results of querySelector that the author wants to re-use.
The trick about convention is that it's not enforced globally, so you still need to check how it's used if you come across it in a project.
It can be used however you like, the $ is just another character that is usable in a variable, like _ is.
Generally though, what I've seen it used for:
No, if he did mean something similar to $$var in PHP.
In js, I use camelCase for naming, and sometimes I use $ as prefix for the variables those refer to DOM elements.
$ has some special meaning in jQuery, not in vanilla JS
If you prepend $ to variable name it means that the specific variable will contain a jQuery Object.
What kind of caching? The $ is just part of the variable name and afaik has no special meaning.
Personally, I use $ to denote function parameters. It looks a little strange at first, however I received positive feedback from my colleagues, since it makes it easier to keep track of what is assigned to what.
// for example, assigning a new value to an input parameter
// is really bad, however easy to detect because of the notation
function foo($bar, $baz) {
// don't do the following
// $bar += 1;
// instead create a new local variable
const myBar = $bar + 1;
// because someone else might have to extend the function
// further down and doesn't see that you changed the parameter
// so, in the long run, you can prevent bugs and extra time
doSthElse($bar, myBar);
}
^personal experience. I once changed a parameter and two years later had to debug the code, because my additional code seemed correct, but it would just not work.
Software Engineer, Technical Consultant & Mentor
Nathan Chase
Designer/Front-End Dev
I see a lot of devs/codebases use
$eventinstead ofevent- for whatever reason. Perhaps just to signify that it's a DOM interface?