4

As javascript developers we all have to write a lot of for loops. Before a couple of months I saw an alternative syntax, which I really liked. However, I'm now interested, is there any other nice way.

Let's say that I have an array of data representing users in a system. What I did before is:

var users = [
    { name: "A"},
    { name: "B"},
    { name: "C"},
    { name: "D"},
    { name: "E"}
];

var numOfUsers = users.length;
for(var i=0; i<numOfUsers; i++) {
    var user = users[i];
    // ...
}

There is one additional row var user = users[i];. Normally I feel more comfortable if I have user instead of users[i]. So, the new way:

for(var i=0; user=users[i]; i++) {
    // ...
}

I'm also wondering if the second approach produces problems in some of the browsers. One of my colleagues reported that this syntax is a little bit buggy under IE.

Edit: Thankfully, the answers below pointed me out to the right direction. If some of the elements of the array is falsy then the loop will stop. There is some kind of solution:

for(var i=0; typeof (user=users[i]) !== "undefined"; i++) {
   // ...
}

But that's too much for me. So, I guess that I'll use this syntax only when I'm 100% sure that all the elements are truly (which means never :)).

3
  • re "only when I'm 100% sure that all the elements are truly (which means never :)" - of course you should have some knowledge how your data looks like and you may depend on it; it's called a "precondition"
    – Kos
    Nov 8, 2013 at 8:17
  • My experience shows me that I should expect everything. Even if I define manually the data, something may go wrong.
    – Krasimir
    Nov 8, 2013 at 8:19
  • I'd rather try to detect something going wrong as early as possible, instead of tring to make all other code work with invalid input anyway.
    – Kos
    Nov 8, 2013 at 8:46

4 Answers 4

5

In your “new” approach, you don’t need numOfUsers any more.

As for the potential problems: This approach relies on all users[i] having values evaluating to true for the loop to continue (and user becoming undefined, equal to false and therefor ending the loop after the last user is processed) – but sometimes you might have data where not every record evaluates to true, but “false-y” values might also occur in the data – and in that case, this approach of course fails.

2
  • Aha ... that's why my colleague reported a problem. Probably he has a falsy value inside the array. You are also right for the numOfUsers (copy-paste typo).
    – Krasimir
    Nov 8, 2013 at 7:57
  • There is some code which could solve part of the problem, but it's still not a good idea. (I edited my question)
    – Krasimir
    Nov 8, 2013 at 8:09
2

The problem with this approach:

for(var i=0; user=users[i]; i++) {
    // ...
}

...is that it assumes user won't be "falsey" (0, "", null, undefined, NaN, or of course false) until you've gone past the end of the array. So it'll work well with an array of non-null object references, but if you then get in the habit of using it, it will bite you when you have an array of numbers, or strings, or such.

The other reason not to declare variables within the for construct is that it's misleading: Those variables are not scoped to the for loop, they're function-wide. (JavaScript's var doesn't have block scope, only function or global scope; ES6 will get let which will have block scope.)

On modern JavaScript engines (or with an "ES5 shim"), you can of course do this:

users.forEach(function(user) {
    // ...
});

...which has the advantage of brevity and not having to declare i or numUsers or even user (since it's an argument to the iteration callback, and nicely scoped to that). If you're worried about the runtime cost of doing a function call for each entry, don't be. It'll be washed out by whatever actual work you're doing in the function.

1
  • Thanks. I just wanted to have a dependency-free alternative.
    – Krasimir
    Nov 8, 2013 at 8:00
0

I'm amazed if the second syntax works at all your middle operation should evaluate to true for each loop you want to complete and false as soon as you want to be done looping. As for any issues with your first for loop, a JavaScript is function scoped so that inner var statement will still leak to the containing function (as well as that i). This is different than most other languages that have block scoping. It's not so much of a problem but something to keep in mind if you are debugging.

5
  • It actually works in every browser on my machine and which is more important works under Nodejs where I'm using it very often.
    – Krasimir
    Nov 8, 2013 at 7:52
  • yeah after a while users[i] would start giving undefined, which is falsy Nov 8, 2013 at 7:55
  • It wouldn't be the first time JavaScript has amazed me. I'm going to dig into this one, but my hunch is the problem would come from an array that might coalesce to false when you aren't at the end. Nov 8, 2013 at 7:56
  • What if it's an array of Boolean values? Or ints with a zero thrown in the middle? Nov 8, 2013 at 7:57
  • Yep, that's what CBroe pointed out and I believe that this is the only one problem in that syntax. I'll continue use it, but only when I'm sure that all my array elements are truly.
    – Krasimir
    Nov 8, 2013 at 7:59
0

If you are already using jQuery, you can use the jQuery.each function to loop over your arrays.

In any case you can look at the source code of that function and copy the relevant parts for your own foreach function: http://james.padolsey.com/jquery/#v=1.10.2&fn=jQuery.each

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.