Is it okay to use break with labels in javascript? - javascript

Is there any benefit of doing so and can it lead to readability concerns?

Labels are generally used in JavaScript to break from an outer loop. For example:
while (true) {
while (true) {
if (someCondition) break;
}
}
In this program you'll only break from the inner loop. The outer loop will loop infinitely. Sometimes however you may wish to break from the outer loop instead of the inner loop. You use labels for this purpose:
loop: while (true) {
while (true) {
if (someCondition) break loop;
}
}
That being said if you have lots of nested loops or switch cases then using labels does in fact help with code readability even though it may not actually affect the program itself.
Take the code in this question for example: https://codereview.stackexchange.com/q/14532/15640
Here we have a switch case in a for loop and although it using we never need to break out of the for loop labelling the loop and the switch case might help some people. For others it's just a distraction.
In the end it boils down to your style of programming. Beginners usually like to label everything. More experience programmers find too many comments and labels annoying.
Steve Yegge actually wrote an entire blog post on this. You may find it very interesting: http://steve-yegge.blogspot.in/2008/02/portrait-of-n00b.html
Try coding without comments: http://www.codinghorror.com/blog/2008/07/coding-without-comments.html

While I don't believe in too many absolutes in coding, I will say that it is rare that I'd use a label in Javascript.
In fact, I don't believe I've ever used them at all the language.
Thanks to the powerful structures given, for ... for ... in while do ... while if ... else and the ability to do an early return almost anything that you'd need a label for can be written in a cleaner structure.

I'm hard-pressed to consider a time where requiring nested loops, and breaking the outer by name from within the inner is necessary, versus, perhaps a simple check of a value at the bottom of the outer loop, to decide whether to continue or not...
Typically, that structure is going to be easier to follow than break third_from_outer_loop; or continue loop_that_is_two_loops_higher.
If you're at a point where you're ready to break the outermost loop from the innermost, then why not just return early?

Related

Micro optimization: Returning from an inner block at the end of a function

In languages such as javascript or (maybe?) lua, all functions by default are treated as if they had a return statement at the end:
function() {
// do
return;
}
Is equal to
function() {
// do
}
I'm wondering if returning from an inner block at the end of the function changes anything in the core, the compiling process, the VM.
function() {
if (condition) {
return;
}
// end of function
}
Same question applies to breaking a loop:
function() {
for ( loop ) {
return;
}
// end of function
}
Does the machine "look" for anything when a loop is broken, or a condition check has ended?
This is not a stylistic question, please don't tell me to make code readable.
TL:DR / optimization advice: you don't need to do anything special to gain performance. if(condition) return inside an inner loop is typically at least as efficient as an if(condition)break; to reach the end of the function.
Putting nested loops inside a function so you can use a return as a multi-level break is a good way of being able to express the logic efficiently without a goto, easy for humans and easy for compilers/interpreters.
Making loop conditions more complicated to avoid multiple return statements in one function is not helpful for performance.
Generally no, a return in the middle of a function is not fundamentally different or more or less efficient than reaching the implicit return at the end. And an explicit return at the bottom of a function isn't special either.
(We're talking about void functions that never return a value, I assume. Obviously returning a value is different from not returning a value.)
Restructuring your code to break out of a loop and reach the implicit return at the bottom of a function is not more efficient (but could easily be less efficient in some interpreted languages, especially if they aren't JITed.) e.g. if the interpreter does a jump within the function and then has to do another jump. (A good ahead-of-time compiler or JIT optimizer could see what was happening and make good machine code anyway.)
Some compilers / interpreters may handle a return by just jumping to a common block of cleanup (epilogue) that all return statements share. But tail-duplication is possible: when compiled to machine code, a function can have multiple copies of epilogue + ret instructions, reachable from different paths.
(JavaScript implementations do typically JIT functions to machine code; IDK about LUA. And of course they can inline functions. return statements in functions that get inlined can be just plain jumps, or could get optimized away entirely.)
I'm not exactly sure whether I correctly understood your question, but I'll try to answer it from my point of view.
The return statement in the end of a function declaration indicates to leave the function and return nothing (void). If you omit a return statement, nothing would happen after the actual function execution. Thus, I think the two functions you declared behave in a different way:
function a() {
// executes until the following statement and then breaks
return;
}
function b() {
// executes all statements and afterwards leaves the context where it was called
}
Regarding your question concerning inner blocks like condition checks or loops, I guess these statements could only be "optimized" by a parser somehow if they consist of static values like numbers or strings. As soon as any dynamic values like variables occur, it would be impossible to optimize anything or have an advantage from the inner result statement.
I hope you can get the point of my explanation.

How to execute two jquery events at once [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Why does everyone tell me writing code like this is a bad practice?
if (foo)
Bar();
//or
for(int i = 0 i < count; i++)
Bar(i);
My biggest argument for omitting the curly braces is that it can sometimes be twice as many lines with them. For example, here is some code to paint a glow effect for a label in C#.
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
{
for (int x = 0; x <= GlowAmount; x++)
{
for (int y = 0; y <= GlowAmount; y++)
{
g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
}
}
}
//versus
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
for (int x = 0; x <= GlowAmount; x++)
for (int y = 0; y <= GlowAmount; y++)
g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
You can also get the added benefit of chaining usings together without having to indent a million times.
using (Graphics g = Graphics.FromImage(bmp))
{
using (Brush brush = new SolidBrush(backgroundColor))
{
using (Pen pen = new Pen(Color.FromArgb(penColor)))
{
//do lots of work
}
}
}
//versus
using (Graphics g = Graphics.FromImage(bmp))
using (Brush brush = new SolidBrush(backgroundColor))
using (Pen pen = new Pen(Color.FromArgb(penColor)))
{
//do lots of work
}
The most common argument for curly braces revolves around maintance programming, and the problems that would ensue by inserting code between the original if statement and its intended result:
if (foo)
Bar();
Biz();
Questions:
Is it wrong to want to use the more compact syntax which the language offers? The people that design these languages are smart, I can't imagine they would put a feature which is always bad to use.
Should we or Shouldn't we write code so the lowest common denominator can understand and have no problems working with it?
Is there another argument that I'm missing?
Actually, the only time that's ever really bit me was when I was debugging, and commented out bar():
if(foo)
// bar();
doSomethingElse();
Other than that, I tend to use:
if(foo) bar();
Which takes care of the above case.
EDIT Thanks for clarifying the question, I agree, we should not write code to the lowest common denominator.
Speed of reading...
Aside from what has already been mentioned. At this point, I've already been conditioned to parse if statements with braces and white space. So I read:
if (condition)
{
DoSomething();
}
DoSomethingElse();
Slightly faster than I read:
if (condition) DoSomething();
DoSomethingElse();
I read it a little slower if it looks like this:
if (condition) DoSomething();
DoSomethingElse();
I read this significantly slower than the prior:
if (condition)
DoSomething();
DoSomethingElse();
beause I can't help but read it again just in-case and wonder if the author intended:
if (condition)
{
DoSomething();
DoSomethingElse();
}
Already covered in general, but when it comes to reading the below, I'll be looking into this for quite a while to make sure what the author intended. I may even hunt down the original author to confirm.
if (condition)
DoSomething();
DoSomethingElse();
If it's something small, write it like this:
if(foo()) bar();
If it's long enough to break into two lines, use braces.
I also used to think it's better to only use braces when really needed. But not anymore, the main reason, when you have a lot of code, it does make it more readable and you can parse over the code quicker when you have a consistent bracing style.
Another good reason for always using braces, besides someone adding a second statement to the if, is something like this could happen:
if(a)
if(b)
c();
else
d();
Did you notice that the else clause is actually that of the "if(b)"? You probably did, but would you trust anyone to be familiar with this gotcha?
So, if just for consistency and because you never know what unexpected things might happen when someone else (it's always the others that are stupid) changes the code, I always put braces, because it makes the source code more readable, quicker to parse by your brain. Only for the most simple if statements, like an if where a delegation is made or is switch-like, where you know the clause will never be extended, I would leave out the braces.
Lines are cheap. Processor power is cheap. Developer time is very expensive.
As a general rule, unless I am developing some absolutely resource / speed critical application, I would always err on the side of writing code that is
(a) Easy for any other developer to follow what I am doing
(b) Comment specific parts of the code that may need it
(c) Easy to debug if something goes wrong
(d) Easy to modify if it needs to be in future (i.e. adding / removing code)
The speed or academic elegance of the code is secondary to these factors from a Business perspective. This is not to say I set out to write clunky or ugly code, but this is MY order of priority.
By omitting curly braces in most instances, it for me makes (b), (c) and (d) more difficult (note not impossible however). I would say that using curly braces or not has not effect on (a).
This is not always considered a bad practice. The Mono Project Coding Guidelines suggests not to use curly braces if it's not necessary. The same for the GNU Coding Standards. I think it's a matter of personal taste as always with coding standards.
I prefer the clarity that the curly brace offers. You know exactly what is meant and don't have to guess if someone just goofed and left them off (and introduced a bug). The only time I omit them is when I put the if and action on the same line. I don't do that very often either. I actually prefer the whitespace introduced by putting the curly brace on its own line, though from years of K&R C-like programming, ending the line with a brace is a practice I have to work to overcome if the IDE doesn't enforce it for me.
if (condition) action(); // ok by me
if (condition) // normal/standard for me
{
action();
}
I think it's a matter of guidelines for the project you are working on and personal taste.
I usually omit them when they are not needed, except some cases like the following:
if (something)
just one statement; // i find this ugly
else
{
// many
// lines
// of code
}
i prefer
if (something)
{
just one statement; // looks better:)
}
else
{
// many
// lines
// of code
}
One of the instances where this can bite you is back in the old days of C/C++ macros. I know this is a C# question, but often coding standards carry over without the reasons why the standard was created in the first place.
If you aren't very careful when you create your macros, you can end up causing problems with if statements that don't use the {}.
#define BADLY_MADE_MACRO(x) function1(x); function2(x);
if (myCondition) BADLY_MADE_MACRO(myValue)
Now, don't get me wrong, I'm not saying that you should always do {} just to avoid this problem in C/C++, but I have had to deal with some very strange bugs because of this.
To be blunt I see it as:
Good programmers program defensively, Bad programmers don't.
Since there are several examples above and my own similar experiences with bugs related to forgetting braces then I learned the hard way to ALWAYS PUT BRACES.
Anything else is choosing personal style over safety and that's clearly bad programming.
Joel even mentions this in Making Wrong Code Look Wrong
Once you get bit by a bug because of missing braces you learn that missing braces look wrong because you know it's a potential place for another bug to occur.
I use to think the same way.
Until one day ( why is there always that "one day" that changes your life forever? ) we spend from 24 - 36 hours straight without sleep debugging production code only to find out someone didn't put braces combined with a search/replace change.
It was something like this.
if( debugEnabled )
println( "About to save 1 day of work to some very important place.");
saveDayData();
What came after was
if( debugEnabled )
// println( "About to save 1 day of work to some very important place.");
saveDayData();
It turns out that the system was generating 500 mb of logs daily and we were asked to stop it. The debug flag was not enough so a search and replace println was in order.
Still when the app went to production the debug flag was off and the important "saveDayData" was never called.
EDIT
Now the only place where I don't use the braces is in if/try construct.
if( object != null ) try {
object.close();
} catch( .....
After watching a superstar developer doing that.
I'm quite happy to:
foreach (Foo f in foos)
foreach (Bar b in bars)
if (f.Equals(b))
return true;
return false;
Personally, I don't see why
foreach (Foo f in foos)
{
foreach (Bar b in bars)
{
if (f.Equals(b))
{
return true;
}
}
}
return false;
is any more readable.
Yes, lines are free, but why should I have to scroll through pages and pages of code when it could be half the size?
If there is a difference in readability or maintainability then, sure, put braces in... but in this case I don't see any reason to.
Also, I will always put braces for nested if's where I have nested else's
if (condition1)
if (condition2)
doSomething();
else (condition2)
doSomethingElse();
vs
if (condition1)
if (condition2)
doSomething();
else (condition2)
doSomethingElse();
is terribly confusing, so I always write it as:
if (condition1)
{
if (condition2)
doSomething();
else (condition2)
doSomethingElse();
}
Whenever possible, I use ternary operators, but I never nest them.
I agree that "if you are smart enough to get someone to pay you to write code, you should be smart enough to not rely solely on indentation to see the flow of the code."
However... mistakes can be made, and this one is a pain to debug... especially if you're coming in looking at someone else's code.
I am impressed and humbled that my peers in this field of computer programming (you lot) are not daunted by the prospect of potential bugs when you skip the braces on single line blocks.
I suppose it means I'm not smart. I have made mistakes around this multiple times. I have debugged others' mistakes around this. I have watched software ship with bugs because of this (RDP to a machine running VS2002 and your watch window font will go wonky).
If I look at all the mistakes I've made that could have been avoided with a change in coding style, the list is very long. If I hadn't changed my approach in each of these cases, I probably would never have made it as a programmer. Again, I guess I'm not smart. To compensate, I have been a staunch user of braces on single-line blocks for a long time.
That said, some things have changed in the world that make the "thou shalt use braces on single-line blocks" rule less relevant today than when Moses brought it down to us:
Some popular languages make the issue go away by making the computer read the indentation, just like the programmer does (e.g. Python).
My editor automatically formats for me, so the chances of me getting mislead by indentation is much reduced.
TDD means that if I introduce a bug because I get confused by a single-line block, I'm much more likely to discover the bug quickly.
Refactoring and language expressiveness mean that my blocks are much shorter, and single-line blocks happen much more often than the used to. Hypothetically, with a ruthless application of ExtractMethod, I could possibly have only single-line blocks in my whole program. (I wonder what that would look like?)
In fact, there's a distinct benefit can come of refactoring ruthlessly & omitting braces on single-line blocks: when you see braces, a little alarm can go off in your head that says "complexity here! beware!". Imagine if this was the norm:
if (condition) Foo(); // normal, everyday code
if (condition)
{
// something non-trivial hapening; pay attention!
Foo();
Bar();
}
I'm opening myself to the idea of changing my coding convention to something like "single-line blocks may never have braces" or "if you can put the block on the same line as the condition, and it all fits within 80 characters, omit the braces". We'll see.
My philosophy is if it makes the code more readable, why not do it?
Obviously you have to draw the line somewhere, like finding that happy medium between concise and overly descriptive variable names. But brackets really do avoid errors and improve the readability of the code.
You can argue that people smart enough to be coders are going to be smart enough to avoid bugs that stem bracketless statements. But can you honestly say you've never been tripped up by something as simple as a spelling error? Minutia like this can be overwhelming when looking at large projects.
There are always exceptions, but I would argue against omitting braces only when it's in one of the forms:
if(x == y)
for(/* loop */)
{
//200 lines
}
//rampion's example:
for(/* loop */)
{
for(/* loop */)
for(/* loop */)
{
//several lines
}
}
Otherwise, I have no problem with it.
I occasionally use the very bottom code (multiple using statements), but other than that I always put the braces in. I just find it makes the code clearer. It's blatantly obvious from more than just indentation that a statement is part of a block (and thus probably part of an if etc).
I have seen the
if (...)
foo();
bar();
bug bite me (or rather "me and colleagues" - I didn't actually introduce the bug) once. This was despite the fact that our coding standards at the time recommended using braces everywhere. It took me a surprisingly long time to spot - because you see what you want to see. (This was about 10 years ago. Maybe I'd find it faster now.)
Of course if you use "brace at the end of the line" it reduces the extra lines incurred, but I personally dislike that style anyway. (I use it at work, and have found it less unpleasant than I expected, but it's still a bit unpleasant.)
Out of the three conventions:
if(addCurleyBraces()) bugFreeSofware.hooray();
and:
if(addCurleyBraces())
bugFreeSofware.hooray();
and (which represent any indentation style using an opening and a closing brace):
if(addCurleyBraces()) {
bugFreeSofware.hooray();
}
I prefer the last one as:
I find it easier to read if all the if-statements are written in a uniform way.
It may make the software a tiny bit more robust and bug free. However all modern IDE's and advanced text editors have nice auto-indenting features which I think everyone should use as long as it doesn't mess up comment formatting or go against team standards (in a lot of cases it's possible to create a custom formatting scheme and share it with the team). My point here is that if indentation is done correctly risk of bug introduction is reduced a bit.
I prefer the boolean expression and statement(s) to execute to be on different lines. I like to be able to mark a row for debugging purposes. Even if I'm using an IDE where I may mark a statement and step to it, it's an interactive operation and I might forget where I started to debug or at least it will take me a little bit more time to step through the code several times (as I have to mark the position manually each time during debugging).
Your main arguments against using braces are that they use additional lines and that they require additional indenting.
Lines are (almost) free, minimizing the number of lines in your code shouldn't be an objective.
And indentation is independent of brace usage. In your cascading 'using' example I still think you should be indenting them even when you omit the braces.
I'm a strong believer in writing tidy and concise code, but I would always use curly braces. I find that they are a convenient way of quickly seeing the scope in which a particular line of code exists. There is no ambiguity, it's just explicitly set out in front of you.
Some may say it is a case of preference, but I find the logical flow of a program much easier to follow if it is internally consistent, and I don't believe that it is consistent to write one IF statement like this;
if(x < y)
x = y;
else
y = x;
And another like this;
if(x < y)
{
x = y;
x++;
}
else
{
y = x;
y++;
}
I prefer to just pick one general style and stick with it :)
One of the main issues is when you have regions of one-liners and non-one liners,
along with separation from the control statment (for, if, what have you) and the end of the statment.
For example:
for (...)
{
for (...)
for (...)
{
// a couple pages of code
}
// which for block is ending here? A good text editor will tell you,
// but it's not obvious when you're reading the code
}
I used to be a huge supporter of "curly braces are a MUST!", but since adopting unit testing, I find that my unit tests protect braceless statements from the scenarios like:
if (foo)
snafu();
bar();
With good unit tests, I can confidently omit curly braces for simple statements to improve readability (yes, that can be subjective).
Alternatively, for something like the above, I would likely inline that to look like:
if (foo) snafu();
That way, the developer who needs to add bar() to the condition, would be more apt to recognize the lack of curly braces, and add them.
Okay, this is an old question that has been answered to death. I have something to add.
First I just have to say USE THE BRACES. They can only help readability, and readability (for yourself and others!) should be very high on your priority list unless you're writing assembly. Unreadable code always, always leads to bugs. If you find that braces make your code take up too much space, your methods are probably too long. Most or all of any method should fit within one screen height if you're doing it right, and Find (F3) is your friend.
Now for my addition: There is a problem with this:
if (foo) bar();
Try setting a breakpoint that will only be hit if bar() is going to run. You can do this in C# by putting the cursor on the second half of the code, but that is not obvious and is a bit of a pain. In C++ you couldn't do it at all. One of our most senior developers working on C++ code insists on breaking 'if' statements into two lines for this reason. And I agree with him.
So do this:
if (foo)
{
bar(); //It is easy to put a breakpoint here, and that is useful.
}
Let's say you have some code:
if (foo)
bar();
and then someone else comes along and adds:
if (foo)
snafu();
bar();
According to the way it's written, bar(); is now executed unconditionally. By including the curly braces, you prevent this kind of accidental error. Code should be written in such a way as to make such mistakes difficult or impossible to make. If I was doing a code review and saw the missing braces, especially spread across multiple lines, I would create a defect. In cases where it is justified, keep it on one line so that the chance of making such an error is again kept to a minimum.
I always omit them when appropriate, such as in your first example. Clean, concise code I can see and understand by glancing at is easier to maintain, debug and understand than code I have to scroll through and read line by line. I think most programmers will agree with this.
It is easy for it to get out of hand if you start doing multiple nesting, if/else clauses and so on, but I think most programmers should be able to tell where to draw the line.
I see it kind of like the argument for if ( foo == 0 ) vs if ( 0 == foo ). The latter may prevent bugs for new programmers (and maybe even occasionally for veterans), while the former is easier to quickly read and understand when you're maintaining code.
Reducing lines is not really a good argument for dropping braces. If your method is too big, it should probably be refactored into smaller pieces or restructured. Doing that will no doubt increase readability more than simply taking out braces.
Use some personal judgement.
if (foo)
bar();
is fine by itself. Unless you're really worried about morons putting in something like this later:
if (foo)
bar();
baz();
If you're not worried about morons, you're fine (I'm not -- if they can't get basic code syntax right, this is the least of their problems)>
In exchange, it's a lot more readable.
The rest of the time:
if (foo) {
bar();
baz();
}
Which has been my favorite as long as I can remember. Additionally:
if (foo) {
bar();
baz();
} else {
qux();
}
Works for me.
Vertical space by itself isn't terribly relevant, readability is. The opening brace on a line by itself just stops the conversation for a syntactic element, until your eye moves down to the next line. Not what I like.
in order to keep the code with braces from taking up lots of space, I use the technique recommended in the book Code Complete:
if (...) {
foo();
bar();
}
else {
...
}
Most times it is ingrained as a coding standard, whether for a company or an FOSS project.
Ultimately someone else will need to grok your code and it is a major time drain for each developer to have to figure out the specific style of the section of code they are working on.
Also, imagine that someone is going between Python and a Cish language more than once a day... In Python indenting is part of the block symantics of the language and it would be quite easy to make a mistake like the one you quote.
Err on the side of more secure - just one more bug you potentially won't have to fix.
I personally feel more secure if all of my blocks are wrapped in curlys. Even for one-liners, these are simple notations that easily prevent mistakes. It makes the code more readable in the sense that you clearly see what is in the block as not to confuse the body of the block with the following statements outside of the block.
If I have a one-liner, I typically format it as follows:
if( some_condition ) { do_some_operation; }
If the line is just too cumbersome then use the following:
if( some_condition )
{
do_some_operation;
}

JsHint W083 Don't Make Functions in Loop and jQuery's $.each() function

I'm currently using JsHint and am receiving warning W083: "Don't make functions within a loop". I read this post from JsLint Error Explanations and understand why you should not do this, which essentially boils down to the asychrnonous nature of JavaScript and the potential for variables to be overwritten.
However, I also read in a few other posts here on SO that although this is a faux pas it does not always lead to bugs depending on the situation.
My situation in particular that JsHint is complaining about is a for-loop that uses the jQuery $(selector).each() function within it. This function takes a function as a parameter. Below is a snippet of the code that I'm concerned about. Don't worry about what it actually does+ since I'm really just using this as an example:
for (var i = 0; i < sections.length; i++) {
disableSectionState[sections[i].name] = {};
$('.' + sections[i].name).each(function (index, element) {
var id = $(element).attr('id');
disableSectionState[sections[i].name][id] = $(element).attr('disabled');
});
if (sections[i].isChecked) {
$('.' + sections[i].name).attr('disabled', 'disabled');
}
}
Essentially, this is just a nested for-each loop within a for-loop, so I didn't think this would be too dangerous, but I'm obviously not familiar with all of the quirks in js.
As of right now, everything is working properly with this function in particular, but I wanted to ask the community about the dangers of this using jQuery's each function within a loop.
To prevent this being marked as a dupe I did see this SO question, but the only answer doesn't go into any detail or explain anything, and based on the comments it looks like an XY problem anyway. I'm more interested in the why this is when at it's core is that it's essentially a nested loop.
Is it really that much safer for this function to be extracted and named outside of the loop? If I copied the loop counter to a variable in scope of the anonymous function, would that eliminate the potential danger of this design? Is that function executed completely asynchronously outside of the main for-loop?
+In case you're actually interested: This code is used to determine if certain fields should be disabled at page load if certain options are enabled.
The problem isn't using jQuery's each within the loop, it's repeatedly declaring a function. That can lead to some odd closure issues (the function closes on a reference to the loop counter, which still gets updated and can change) and can be a non-trivial performance problem on less clever VMs.
All JSHint is asking you to change is:
function doStuff(index, element) {
var id = $(element).attr('id');
disableSectionState[sections[i].name][id] = $(element).attr('disabled');
}
for (var i = 0; i < sections.length; i++) {
disableSectionState[sections[i].name] = {};
$('.' + sections[i].name).each(doStuff);
if (sections[i].isChecked) {
$('.' + sections[i].name).attr('disabled', 'disabled');
}
}
Most of the dangers come when you're calling something asynchronously from within a loop and close over the loop counter. Take, for example:
for (var i = 0; i < urls.length; ++i) {
$.ajax(urls[i], {success: function () {
console.log(urls[i]);
});
}
You may think it will log each URL as the requests succeed, but since i probably hit length before any requests have come back from the server, you're more likely to see the last URL repeatedly. It makes sense if you think about it, but can be a subtle bug if you aren't paying close attention to closure or have a more complex callback.
Not declaring functions within the loop forces you to explicitly bind or pass the loop counter, among other variables, and prevents this sort of thing from accidentally cropping up.
In some more naive implementations, the machine may also actually create a closure scope for the function every iteration of the loop, to avoid any potential oddities with variables that change within the loop. That can cause a lot of unnecessary scopes, which will have performance and memory implications.
JSHint is a very opinion-based syntax checker. It's kind of like deciding which type of citations to do on a paper MLA or APA. If you go with one, you just follow their rules because, most of the time, it is "right", but it's rarely ever wrong. JSHint also says to always use === but there may be cases to use == instead.
You can either follow the rules or ignore them with the following
// Code here will be linted with JSHint.
/* jshint ignore:start */
// Code here will be ignored by JSHint.
/* jshint ignore:end */
If you are going to use JSHint, I would just comply. It tends to keep the code a little more consistent, and when you start trying to work around one warning or error, it tends to start creating a bunch more
Is it really that much safer for this function to be extracted and named outside of the loop?
In practice, yes. In general, on case by case, maybe not.
If I copied the loop counter to a variable in scope of the anonymous function, would that eliminate the potential danger of this design?
No.
Is that function executed completely asynchronously outside of the main for-loop?
Pretty sure it is.

if..else vs if(){return} [duplicate]

This question already has answers here:
Using 'return' instead of 'else' in JavaScript
(13 answers)
Closed 5 years ago.
In the following example - given that the return value isn't of any importance - is there a reason to prefer either method over the other?
// Method 1
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
} else {
// or here
}
return true;
}
// Method 2
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
return true;
}
// or here
return true;
}
It seems that best practices (mostly by places I've worked for) is to set default values at the top of a method or function and only change those values if some condition occurs. Thus, the use of else is not needed so Method 2 is preferred.
Since the example is JavaScript, special attention needs to be paid in regards to code size. So Method 2 would create less code for the same functionality, furthering its argument as the preferred.
However, if you have more than 2 possible conditions, an else or else if cannot be avoided. However, most places I've worked prefer a Switch Case in these situations.
I would prefer Method 1 because it is less confusing to read. Also, less duplicate code.
I would base my decision on clarity of code and readability, i.e.:
Choose method 1 when you need to do more stuff in the block after the if-block.
Choose method 2 when you only need two blocks of code, it's then clearer to read
Choose method 1 again in cases where you explicitly think your readers wouldn't understand your cryptic code without the word "else"; this is common when the blocks become larger than a few lines.
Many of today's programmers consider less indentation easier to read and I agree. In which case general preference should go to using the second method.
I would recommend method 1 as it is more readable and self documented.
Any modern browser's interpreter should eliminate any performance advantage in either direction.
There are a couple of reasons method 1 is preferable that haven't been mentioned yet. Having a single point of exit makes any future modifications that require an action common to both branches easier and less likely to be buggy (because the author missed the early return. Similarly, in some cases it makes debugging easier, by providing a common place to put a breakpoint or alert().
Readability here really depends on the role of the function.
If this function will ALWAYS return true, then I would prefer the Method 1 It is clear because it only returns in one place, and it is easy to see it will always be true.
In the above case, Method 2 is more confusing. It returns in multiple places, and is more confusing thusly. Consider a developer unnecessarily traversing possible branches and then seeing how they affect the return value. In this simple case, it is not as big of a deal, but when you get more elaborate conditionals, I would really avoid this approach.
I would only use Method 2 if you have very little code in the if block. Such as something that would deal with an edge case.
Hope that helps.

Exceptions in javascript, should I use them and how?

I've been told a few times that it's "bad" to use exceptions in javascript. Haven't really been told why it's bad, but inestead that I should use break, continue and return instead.
Which is fine, except I don't need to return/break/continue, I need to throw. I have a case where I have iterator functions nested in each other, each one returns the next value on call, so I use an exception to indicate that there's nothing more to iterate : seems like a logical way to do it, makes the code clean and works perfectly in practice. Is there really any reason not to use exceptions in js?
Second question, when I'm using exceptions, what kind of objects should I throw? For errors I'll obviously throw instances of Error, but for special cases (stop iteration, etc) I needed a quick way to check for those specific exceptions, and what I did is simply define an empty named function (function StopIteration(){}) and since functions are compared by reference I can always check if it's my special case or I should just rethrow. Is there a better or more idomatic way to do this in js? Should I really try to refactor my code avoid using exceptions?
Thank you
It sounds like you're searching through a multidimensional space using nested loops, which is a fairly common thing to program. It's tempting to throw an exception from the innermost loop when the target is found which then gets caught by a "catch" block around the outermost loop but this often considered poor practice.
Language designers are aware of this pitfall so they allow us to give labels (names) to loop structures so that we can break from them (or continue to them). Consider this example:
function findValueInMatrix(value, matrix) {
var r, c, coords, rows=matrix.length, cols=matrix[0].length;
found: // Label the outer loop as "found" so we can break from it.
for (r=0; r<rows; r++) {
for (c=0; c<cols; c++) {
if (matrix[r][c] == value) {
coords = [r, c]
break found; // Exit the loop labeled "found".
}
}
}
return coords;
}
You can find more information in this post about breaking from nested loops.
This jsPerf test case also demonstrates that breaking to a label is nominally faster than throwing an exception (presumably in most browsers).
exception handling is in general slower than normal evaluation and only for exceptional situations
for stopping iterations you are better of defining a hasNext or isEmpty function for an ending condition or return a sentinel value (like undefined) when there are no more elements so the loop becomes
//with hasNext
while(it.hasNext()){
var val = it.next();
//...
}
//or with a sentinal undefined
while( (val = it.next()) !== undefined){
//...
}
For some people, throwing exceptions to indicate that there is no more values is a bad style; exceptions are made for exceptional behaviour.
Moreover, exception handling is generally slower than simple tests.
The difference is really minor (and maybe does not even exist) if the thrown instance is not created everytime. So having a constant StopIteration and throwing it is in fact quite fast.
For your problem, you might want to see https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators (they use exceptions to stop iteration).
I found that in dynamically typed languages exceptions are used for this kind of purposes too.
Throwing an exception to break out of a nested recursive search/walk is the easiest and more elegant way to go.
Say you walk a tree, recursivelly calling a function to handle the current node, calling again for each of its children and so on.
As you process each node, you might want to completelly break the whole call stack and return the found value (or stop iterating in general), breaking out of all the loops that are waiting in previous calls. Mind you that these previous calls might be costly in processing & memory, but useless if you "found" your result. Throwing an Exception is the most efficient and simple way to achieve this, but of course it needs attention.
For simple (even nested) loops its a overkill and is rightly touted as an anti-pattern.

Categories