Last Updated: February 25, 2016
·
978
· rabidaudio

An elegant way to do reverse order C-style for loops

for(var i=array.length; i-->0; ){
   console.log(array[i]);
}

This is awesome because it looks like an arrow i --> 0 but actually you are decrementing i after testing i>0. C/C++ programmers probably knew this already, but I bet there are some web devs out there that will find this as cool as I did. Just don't forget the second semicolon (basically you are leaving the third argument, the code to run at the end of each loop, blank).

I can't take credit for this. I found it on Stack Overflow (via user bobince).

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside