AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |
Back to Blog
For of loop javascript8/29/2023 (And the ++i syntax says “add 1 to my variable, *THEN* execute this statement”. The i++ syntax says “execute this statement, *THEN* add 1 to my variable”. The increment operator is just a way of saying “add 1 to my variable” Good article, but there’s some important distinctions here. I’m still learning, and I’m happy to correct any mistaken views. And by all means, do the necessary research before you take my word as gold. I should point out - as I often do when I write about JavaScript - that I don’t consider myself an expert in this area, so if you have any corrections or supplementary information to contribute to this topic, please do so in the comments. So that’s it, there’s five practical improvements made to a simple for loop, and more importantly, some underlying principles that can help you to write cleaner and more efficient code on a larger scale.Īs a side point, there aren’t many examples online or otherwise that will present a for loop using the tips described above, but I think it would be good if most developers adopted these practices if they do indeed contribute to better performance, readability, and maintainability. Notice also that I’m subtracting one from the starting value and letting the loop go down to zero, to account for zero-based indexing. Of course, you might have a case where decrementing your loop would not work, so this is just something to consider should the situation allow for it. Now the different parts of the loop’s instructions have been reversed and we’ve even eliminated the use of a second variable, since we know that we’re just going down to 0. Var anchors = document.getElementsByTagName("a") I think it’s safe to say that most beginner to intermediate JavaScript developers will write their for loops like this: The performance difference seems to be very small. Update (September 7, 2012): If you’re interested, you can check out a jsperf I set up that compares the original code and the final optimized version.
0 Comments
Read More
Leave a Reply. |