JavaScript Loop Challenge

With all the new methods that were added to JavaScript arrays a few years ago, there is now no reason (except possibly efficiency) for using loops in your JavaScript for any processing involving arrays or anything that can be converted to an array.

Every piece of JavaScript code that I have seen recently that uses one or more loops could be easily rewritten to eliminate the loop.

I know that loops still have their uses in JavaScript but finding a realistic real world example or even a “homework question” where there is no alternative to using a for or while loop is getting more difficult. The examples that I have for loops on my “JavaScript By Example” web site are all ones that could be done in less code without a loop.

Does anyone have any suggestions for something that can only be done in JavaScript using a loop so that I can update those example pages on the site to something more realistic?

As no one has replied to this thread I assume that no one can think of any circumstances where you need to use a loop in JavaScript any more (other than for efficiency considerations).

Sorry, I haven’t seen your website. Maybe you could pm me the link?

It is the red link in my signature.

Oh, thats the pitfall of Tapatalk is that it doesn’t show signatures. (Usually the right thing to do 90% of the time.) I’ll try to remember to look next time I’m at the office.

Not yet.
If I run across something in the course of my travels, I’ll be sure to post back.

One reason for preferring for loops however, is readability / comprehension.

E.g. from a recent thread:

var divs = document.querySelectorAll('div');

var num = 0;
for (var i=0; i<divs.length; i=i+1) {
    if (divs[i].style.backgroundColor === "green") {
        num = num + 1;
    }
}

console.log( "There are " + num + " green divs" );

This is easy to understand (also for a beginner).

This, however:

var num = Array.prototype.filter.call(document.querySelectorAll('div'), function(el){
    return el.style.backgroundColor === "green"
}).length;

console.log("There are " + num + " green divs");

does the same thing, but the use of Array.prototype.filter.call is off-putting for some.

Agreed. Simple and readable code trumps clever code.

This is great challenge. I’m working on canvas, audio, WebGL and file execution. Everything is involving with loop of ArrayBuffer. The fastest loop browser can execute is the greatest one.

I agree. The following is just about as simple a practical example of using the Array.filter() method as I can think of and so is the sort of code where filter() should be used. If such a simple use of the command were considered to be too complicated or clever and so should be avoided then I am left wondering what the method is supposed to be used for as I can’t think of a simpler practical example of its use.

var num = Array.prototype.filter.call(document.querySelectorAll('div'), function(el){
    return el.style.backgroundColor === "green"
}).length;

console.log("There are " + num + " green divs");

That code is using filter for its intended purpose of extracting a subset from the content - in this case those where the background colour is green. The only part that is possibly clever is that the extracted array itself is immediately discarded as the only thing needed from it is the length.

I suppose that using or not using such simple commands is part of what distinguishes an intermediate level JavaScript programmer (who has learnt these intermediate level commands) from the newbie still trying to understand the basics.

Now the following comes a lot closer to being “clever code” that is not simple and readable:

populateArrayWithIntegers = function(n) {return Object.keys(Object(0+Array(n)));};

With that code you are far more reliant on the function name telling you what the code does.

 numArray = populateArrayWithIntegers(20)); // numArray =  [0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20] 
var numbers = [1,2,3,4,5,6,7,8,9];

var divisibleByTwo = numbers.filter(function(num){
	return (num % 2 === 0);
});

That’s a very slightly simpler example of using Array.filter() - but only because you are using Array.filter() by itself rather than in combination with Function.call() . It is also a far less practical one. I would expect that wanting to reference all the elements in a web page with a particular attribute having a specific value would occur far more frequently than needing to extract numbers that match a particular criteria (such as being even). So I’d say that what it gains in simplicity it more than loses in practicality. The earlier example checking the background colour is the simplest use of filter that you could find useful for just about every web page you write, there’d be very few web pages where you’d need to extract even numbers from an array.
.
Also since Function.call() is intended to be used in combination with other object’s methods in order to borrow methods the combination of Array.filter() with Function.call() is about as simple a use of Function.call() as you are likely to find even if simpler uses for filter by itself exist…

The ONLY thing that makes the use of the filter.call hard to read is that most people trying to write JavaScript have not learnt all of the methods that are available on the built in objects and how to use them - but then most people still write their JavaScript as if Netscape 3 or 4 was the target browser…