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)
Related
For example, I have code like this:
var Player = function(param){
var self = {
x:0,
y:0,
spdX:0,
spdY:0,
id:"",
}
self.hp = 24;
}
Do I need to add hp inside var self = {}?
I believe others have misunderstood the question. If I understand correctly, you are asking about any potential issues with dynamically adding properties to an existing object (vs. when first declaring the object). The answer is that it is fine to do, is common JS practice and should have no negative performance impact.
This is a perfectly reasonable question if you are coming from a statically typed language background. For example, in TypeScript, you cannot add properties to an object after it has been defined (see this question). This is done for:
Type safety (far and away the main reason)
Performance (possibly).
No
It's completely alright. Relax. Your code isn't going to explode. Breathe. Breathe! Okay, now that you're settled down...
Performance wise, it's the same*: Performance test.
Syntax wise, they are both used in major documentation sites: developer.mozilla.org & W3Schools
*Well as close as it gets
Something is wrong with my code or with plovr. I went to JSLint to get some help. However, JSLint seems to consider this as a fatal error and refuses to check more of the code:
for (var i = 0; i < data.length; i += 4) {
Why? I like this way of declaring "I".
JSHint does not seem to be an alternative if you are on Windows. I am trying The Online Lint at the moment. I have a feeling that this bug will be a bit difficult to find so I would be glad for suggestions about good code checkers.
I agree with Niet the Dark Absol that the tool is opinion-based. Reflect on all the rules it imposes and whether they actually make sense in your specific project or not. It's also not the only "lint" tool for JavaScript. Maybe ESLint or another such tool is more suited to your needs.
But I also disagree with him: It is not good practice to declare all your variables at the start of your function, especially not if the function is rather long, since this makes comprehension of your program much harder. IMHO this holds regardless of how the scoping of JavaScript works: It's not about program semantics, it's about code readability!
I would argue that a variable should be declared as close to its first use as possible (i.e. in your case: in the for loop). This ensures that someone reading your code (a colleague or yourself three months from now) has too keep as little information in their head as possible. Declaring all your variables at the start forces the reader to keep all those variables in mind throughout the entire function. Questions like "what's the current value of this variable?" or "what is its purpose?" become harder to answer.
Furthermore, you are much more tempted to reuse a variable for more than one purpose. This is not only confusing, but also dangerous! Values might "leak" from the first use to the second. This can lead to subtle, hard-to-debug problems.
My personal opinion is that JSLint is retarded. But opinions may vary on that sensitive topic.
— dystroy, 45 secs ago
Hey, that's actually a valid point. JSLint is entirely constructed on opinion, and it not the word of god.
However, general good practice is to declare all your variables in one place, at the start of the function block they are in:
function doSomething() {
var a, b, c, d;
a = 1;
c = 10;
for( b = a; b < c; b++) {
d = b*2 + a-c;
alert(d);
}
}
Because creating a bar in the for loop creates a global var. it's one of those things that JavaScript does and most people don't realize. And if you don't and you or someone else creates that same var in the scope of that function or global scope then that my friend would be one of the famous JavaScript foot guns.
Considering this:
var getToDaChoppa = false;
var warIsHell = function() {
// Write your do/while loop here!
do {
console.log("I can't my legs omg my LEGS");
} while (getToDaChoppa);
};
warIsHell();
and this
var getToDaChoppa = function() {
var getToDaChoppa = false;
do {
console.log("I can't my legs omg my LEGS");
} while (getToDaChoppa);
};
getToDaChoppa();
I really like to know which piece of code is better from a technical standpoint. (Lower memory usage, garbage generation, etc). I'm pretty n00b to js, but I want to make sure I'm writting the best possible code.
From my limited experience the second snippet will generate double garbage than the first one, but in the other hand, the first one uses double the memory than the second one, so I was wondering what is the best approach here. Ofc if you need to swing around variable values, ¿I understand first one is more versatile?, but I cannot fully comprenhend the pros / cons of both methods.
Any little explanation will be of great help o:)
The main difference I see between your two functions is that the first one uses a global (or at least external) variable while the second one use a local variable.
Then the rule is simple : don't declare a variable in an external scope if you don't use it in that scope. Always declare your variables in the most internal scope. This makes the code more readable and limits the risks of collision. Trying to reduce the garbaging by making it external is terrible practice and useless unless, in a very specific case, you proved by profiling you have a problem and it is solved that way (then... I won't probably trust you...).
A second rule would be : don't shadow variables if possible. Shadowing the name of the function with a boolean variable is very confusing.
Here's a "fixed" code :
var getToDaChoppa = function() {
var finished = false;
do {
// some code, which hopefully will at some point set finished to true
} while (!finished); // you wanted a !, here, no ?
};
getToDaChoppa();
I would say that the second approach is better simply because you're keeping the condition variable inside the function scope, thus not polluting the global scope.
Also, don't name the variable with the same name as the function.
I often works with jquery and sometimes my code contains lot of repeated css class names, like:
$('#div1').addClass('funny-class');
...
$('#div2').addClass('funny-class');
...
$('#div1').removeClass('funny-class');
etc... I was asking to myself if is it worth to clean the code using pseudo constants like:
var constants = {
FUNNY: 'funny-class'
}
...
$('#div1').addClass(cnst.FUNNY);
$('#div2').addClass(cnst.FUNNY);
$('#div1').removeClass(cnst.FUNNY);
First: minimization. If "constants" is a local var (hidden into a scope) probably the minimizer could replace the occurrence of "constants.FUNNY" with something minimized like "a.B".
Second: speed. The code with "constants" is faster than the first one?
What do you think?
You can use Google's closure compiler with advanced optimization to identify commonly repeated strings and replace them by constant variable references. But this optimization is marginal; if you want to improve your code you'd get a better improvement by caching jQuery objects (this is a matter usually overlooked by many programmers):
var $div1 = $('#div1');
var $div2 = $('#div2');
$div1.addClass('funny-class');
$div2.addClass('funny-class');
$div1.removeClass('funny-class');
It might not be noticeable as performance, but it is always a good practice to use constants instead of strings because you can easily modify the value by changing the constant's value.
Yes, a minifier will probably reduce the constants.FUNNY variable, where-as it probably won't detect the re-use of 'funny-class' and assign it to a variable.
The speed difference will be so marginal you shouldn't care. On one side you have to resolve the variable in the scope chain (very quick), but in the other you have to create a String primitive (also quick).
The benefits of having your constants object is if you decide to change the name of the class you assign, you only have to do it in one place, not 3; this is the sole benefit you should be considering... not a 0.0000000000000001 second speed difference.
Putting it in variables can provide you with a certain amount of "central control" rather than performance.
However, putting them deeply in an object will incur a performance penalty. Keep them near the surface as possible to avoid the overhead in scope resolution. (it's minimal, but still an overhead)
//this one is so deep:
constants.foo.bar.baz.bam
//this is just 1 level deep:
constants.bam
Also, I'd worry more about the jQuery calls you are making
//two calls to #div1!
$('#div1').addClass(cnst.FUNNY); //$() for div1
$('#div2').addClass(cnst.FUNNY);
$('#div1').removeClass(cnst.FUNNY); //another $() for div1
//do this instead
var div1 = $('#div1') //reference div1 once in a local variable
div1.addClass(cnst.FUNNY); //use the reference to the object
$('#div2').addClass(cnst.FUNNY);
div1.removeClass(cnst.FUNNY); //use the same reference to the object
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.