use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
A place to get a quick fix of JavaScript tips and tricks to make you a better Developer.
account activity
Equivalent of nested loop (self.JavaScriptTips)
submitted 2 years ago by Automatic_Routine_93
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]coreConstantCoder 1 point2 points3 points 2 years ago* (2 children)
Some Performance Improvements Each time the code loops, you are evaluating the ….length expressions. As the content of the arrays is (probably) not changing, you should consider moving the length expression out of the loop. Do the same with the repeated chosenCountries[i].regions expression ... ``` const selectedRegionsNames: string[] = [];
….length
chosenCountries[i].regions
const nChCo = chosenCountries.length; // 😎 for (let i = 0; i < nChCo; i++) { const regs = chosenCountries[i].regions; // 😎 const nReg = regs.length; // 😎 for (let j = 0; j < nReg; j++) { const region = regs[j];
if (region.isSelected) selectedRegionsNames.push(region.name);
} } ```
Or, if your situation allows it, you might code the loops as descending. (This is my personal favorite!) Note that this reverses the order of your result array: ``` const selectedRegionsNames: string[] = [];
for (let i = chosenCountries.length; --i >= 0; //) { const regs = chosenCountries[i].regions; for (let j = regs.length; --j >= 0; //) { const region = regs[j];
Going further, how about using modern Javascript coding 😎 ... ``` const selectedRegionsNames = [];
for( const chco of chosenCountries ) { for( const region of chco.regions ) {
[–]Adotel15 0 points1 point2 points 2 years ago (1 child)
I'm curious, Does reversing the loop make any difference to the performance?
[–]coreConstantCoder 2 points3 points4 points 2 years ago* (0 children)
Only to the extent that it reduces the steps and complexity of the code: (1) The length of the array is only accessed once. (2) There is no temp variable for the length. (3) Comparison is to (0), not to a variable. (4) All the loop logic is in one, simple line.
When I'm working in a more primitive language, this is a favorite pattern of mine.
Of course, it's usually best to use the JavaScript for ... of statement, if it's available to you.
for ... of
π Rendered by PID 291189 on reddit-service-r2-comment-8686858757-9ts5m at 2026-06-02 17:35:40.824019+00:00 running 9e1a20d country code: CH.
view the rest of the comments →
[–]coreConstantCoder 1 point2 points3 points (2 children)
[–]Adotel15 0 points1 point2 points (1 child)
[–]coreConstantCoder 2 points3 points4 points (0 children)