Caching in jquery: Which is better? $ or no $ - javascript

i have a simple question about caching, this kind of confuses me lol
Im not sure if it depends on if your using handlers or not but...
is there any difference between these two?
var $something = $('.something');
or
var something = $('.something');
and also, is it possible to do this (depending on the correct way)
var something = $('something'),
somethingElse = $('somethingelse');
or this way
var something = $('something');
var somethingElse = $('somethingelse');
just want to be sure im heading in the right direction.
It's been bothering me. I've seen it done both ways actually, but i don't know which is right, or if either are wrong. I'm sure someone knows for sure though :)

Prefixing variables with $ is only used to remind the programmer (or others) that the variable holds a jquery object. It isn't a 'javascript thing' and does not provide any additional functionality. It's a good idea though :)
All the code you posted is valid.

It's your choice. Many people (including myself) prefix variables with $ to indicate that the variables represent jQuery objects (because $ is shorthand for jQuery). If you think it helps you along the same lines, then you're free to prefix your variables as such.
Declaring multiple variables comma-separated with a single var keyword is legal JavaScript.

Related

Javascript naming convention for related DOM elements?

I ask because I'm writing an Angular directive requiring me to reference the parent and grandparent element. This means I end up with long names for something like the 'grand parents' innerheight. Something like:
var grandParentInnerHeight = $grandParent.innerHeight();
A friend suggested using nth to name these, but using numbers also seems wrong when it comes to naming variables.
And I know some people might suggest to restructure my code so I don't need the grand parent, but in this case its necessary.
Any ideas?
I've seen people use abbreviations like
var gpInnerHeight = foo;
or
var grandPInnerHeight = foo;
But personally, I find no problem in writing the full name of a variable. It makes it clear to understand, but just takes a couple more ms to write it.
Also, for JQuery, I've seen some people who want to distinguish between JavaScript variables and JQuery variables by putting a $ in front of them like this.
var $grandParentInnerHeight = foo.innerHeight();
Here's a website that goes over some naming conventions that I see as useful.
Click me

Consequences of missing a comma when declaring multiple variables in javascript?

I'm new to javascript and have picked up an application developed by another team recently.
In this program in one place where they declare several variables at once there is a missing comma like:
var me = this,
missing = this.missingComma
grid = something.Something;
What if any are the consequences of there not being a comma after the second entry. The relevant bit appears to work when just running it. The code has no tests and since it's javascript I cant compile it, also I dont really know what its supposed to do so unfortunately 'not falling over' is currently my best guess at 'does what its supposed to do'!
Why does it work? Isn't this a syntax error?
In JavaScript the semi-colons aren't required to indicate the end of a line. A linebreak is sufficient to indicate that the next line is a separate statement rather than a continuation of the previous line of code (as is the case when you use the comma to indicate multiple variables).
Your code is essentially the same as this:
var me = this, missing = this.missingComma;
grid = something.Something;
Since that declares the grid variable without the var keyword, you'd end up with grid being created in the global, rather than the current, scope. That's generally something you want to avoid but it's not going to be the end of the world if it does happen - in this case it may even be intended (though I'd guess not).
Javascript is ubiguitous with a a lot of freedom ;)
Maybe it helps you to understand some peculiarity of JS if you read some additional info about semicolons, commas and newlines in Javascript:
http://www.codecademy.com/blog/78-your-guide-to-semicolons-in-javascript
For the sake of readability, I would suggest you to use the classic approach, anyway.
var me = this;
var you = that;
or at least
var me = this, you = that;
For the rest, I think that Anthony Grist has brought it to the point.
Well even though in javascript the semicolon is not required it is a must now a days, because if you want your JavaScript to get minimized, it must have all semicolons. Minimization puts your complete JavaScript in one line... replacing long variable names with short ones, etc.
On the other hand... back to you question.
If you declare your var inside a JavaScript "namespace" (actually an object) then all the variables are "private" and you could choose to make the ones "public" by using the reveal pattern.
This is a good practice, else all you variables are declared on the windows scope... which actually can then be overwritten by any other part of your page that uses the same variable name, even if you thought it was completely independent.
So you could actually do something like this :
var MyNamespace || {}
// this delcares an object MyNamespace only if it doesn't exists yet
MyNamespace.Logic = function(){
var self = this,
myPrivateVariable = "Hello",
self.myPublicVariable = "World",
self.printHello = function(){
alert(myPrivateVariable +' ' +self.myPublicVariable );
};//this semicolon closes the var statement
};
Now you can use somehwer on you page folowing logic
var newInstanceOnMyLogic = new MyNamespace.Logic()
This is equivalent of writing
var newInstanceOnMyLogic = new window.MyNamespace.Logic();
But your variables myPrivateVariable and myPublicVariable are no longer on the windows context and can't be overwritten
Now if you write something like
alert(newInstanceOnMyLogic.myPublicVariable);
you'll get a "World"
But
alert(newInstanceOnMyLogic.myPrivateVariable );
you'll get an undefined
and
newInstanceOnMyLogic.printHello();
will get an alert of "Hello World"

Declaring variables javascript [duplicate]

This question already has answers here:
Why would a JavaScript variable start with a dollar sign? [duplicate]
(16 answers)
Closed 9 years ago.
I just have a quick question and cant find anything on google. I was going through some code another programmer put together and he declares ALL of his javascript variables with $ in front of them...for instance:
var $secondary;
Is there a reason for this? Could this cause problems in the future if JQuery ever ends up being used. I'm just curious because I was going to clean it up if so.
Is there a reason for this?
Hard to say. Maybe he came from a PHP background where $ prefixes the variables. Maybe he's a jQuery addict. Who knows? You'd have to ask him. That aside, $ is a perfectly legitimate character to use in a JavaScript variable name but as you noted, it could cause issues with jQuery. But that's why jQuery offers a noConflict() option.
I use this convention too keep track of if a variable is storing a JQuery object. So say the function getJQueryObject() returns a JQuery object and I want to store it.
i.e:
var $myJQobj = getJQueryObject();
Makes it clear that $myJQobj is a JQuery object unlike i.e
var myStr = "hello";
The $ as the first character in the identifier doesn't have any special meaning, you aren't invoking a method like $(), it's just a perfectly valid identifier in JavaScript. But the factthat the $ is used in JQuery makes what I was talking about before even clearer.
$ is a valid variable character, and in PHP all variables start with it. It's possibe that that particular developer uses $ as a "flag" to mean "this is a variable". It has no special meaning.
$ just a character that you can use in a variable name. Some people like to use it to denote variables that contain jQuery objects:
var $foo = $('#foo');
var bar = 42;
But that's just a personal preference. It has no special meaning.
its just a convention for jQuery DOM selctions.
var $logo = $('a.logo');
it wont cause any issues - it just lets other devs know that you're working with a jQuery wrapped dom element.
$ is fine for use in JavaScript. PHP uses the same variable syntax so maybe he was used to it from that.

$ae. javascript notation

I am starting to learn jQuery. Looking though the MVC3 project that makes use of Awesome MVC Html helpers, I have stumbled upon a javasript code that I don't know how to understand yet:
$ae.autocomplete('Requestor'
What is $ae is calling a jQuery autocomplete on in this case? ae isn't an element, so this isn't an id or class selector.
P.S. And while you are at it, please let me know what $. as in $.getJSON calls getJSON on?
Assuming that there isn't a typo, $ae is a variable. Since $ is just a javascript function you can assign the result of it to a variable, $ae = $("#myid"). While I don't know that $ae is definitely the result of that, the naming convention ($ at the beginning) makes me suspect that it is.
In jQuery, the $ is a convenient alias for the jQuery object. So $.getJSON() is calling the getJSON() method of the jQuery object. This is pretty confusing at first, but once you get used to it it's nice and concise.
It seems like common practice in jQuery development to use a $ to prefix variables that result from selecting things with jQuery, like this:
var $myList = $('.list-item');
The $ is a legal character to use in variable names, so I guess it's a reminder that the object contains a jQuery wrapped set. It's a good idea to assign the results of your selections to variables if you'll use the selected items again; otherwise you're wasting resources.
In your example, the $ae is the equivalent of something like this:
$('#my-input').autocomplete('Requestor ...

Is that a bad Javascript practice I'm doing here?

for some reason I do that every time because I find it clean. I declare variables on top to use them below. I do that even if I use them only once.
Here is an example (using jQuery framework) :
$("#tbListing").delegate("a.btnEdit", "click", function(e) {
var storeId = $(this).closest("tr").attr("id").replace("store-", ""),
storeName = $(this).closest("tr").find("td:eq(1)").html(),
$currentRow = $(this).closest("tr");
$currentRow.addClass("highlight");
$("#dialogStore")
.data("mode", "edit")
.data("storeId", storeId)
.data("storeName", storeName)
.dialog( "open" );
e.preventDefault();
});
I tend to do that in PHP too. Am I right if I believe it's not very memory efficient to do that ?
Edit: Thank you for all the answers. You have all given good answers. About that code optimisation now. Is that better now ?
$("#tbListing").delegate("a.btnEdit", "click", function(e) {
var $currentRow = $(this).closest("tr"),
storeId = this.rel, /*storing the storeId in the edit button's rel attribute now*/
storeName = $currentRow.find("td:eq(1)").html();
$currentRow.addClass("highlight");
$("#dialogStore")
.data("info", {
"mode" : "edit",
"storeId" : storeId,
"storeName" : storeName
}) /*can anyone confirm that overusing the data isn't very efficient*/
.dialog( "open" );
e.preventDefault();
});
Sorry, are you asking if it's OK to declare variables even if you're using them once?
Absolutely! It makes the code a million times more readable if you name things properly with a variable. Readability should be your primary concern. Memory efficiency should only be a concern if it proves problematic.
As Knuth said,
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
If you're asking more about declaring the variables at the beginning of the function, rather than where they are first used, then Emmett has it right - Crockford recommends doing this in JavaScript to avoid scope-related confusion. Whether it's worth it in PHP is a purely subjective question I'd say, but there's nothing wrong with keeping your PHP and JS coding styles similar.
One more CS quote (from Abelson and Sussman's SICP):
programs must be written for people to read, and only incidentally for machines to execute.
It's not bad practice.
The var statements should be the first statements in the function body.
JavaScript does not have block scope,
so defining variables in blocks can
confuse programmers who are
experienced with other C family
languages. Define all variables at the
top of the function.
http://javascript.crockford.com/code.html
Declaring variables at the top is a good thing to do. It makes the code more readable. In your particular example, you could replace $(this).closest('tr') witha variable, as suggested int eh comments, but in general I find code with descriptive variable names all in one place very readable.
nah, I'd say you're doing exactly the right thing.
As #Caspar says, you could simplify your code by setting $currentRow first and using that instead of $(this).closest("tr") in the other two lines. And there may be a few other things you could improve. But setting vars at the begining of a function the way you've done it is absolutely a good thing.
Particuarly good because you've done it inside the function, so they're local variables, which means they get thrown away at the end of the function, so no memory usage issues there.
If you'd set them as global vars, it might have been more of an issue, although to be honest even then, since you're just setting pointers to an existing object, it wouldn't be using a huge amount of memory even then (though it would be polluting the global namespace, which isn't good)

Categories