- A for loop can be composed of 4 different pieces. Not all of them are required.
- begin — where you declare a variable to be initialized at the beginning of the for loop (let idx=0;). Did you know i is for index and j is just a letter that looks like i?
- condition — which if true allows the loop to then execute the body and if false ends the loops (idx < arr.length;).
- body — is where you write the code to be run when the condition evaluates to true (sum = sum + arr[idx];).
- step — which executes after each iteration of the body (idx += 1).
So you’re like cool Corey, so you’ve been learning algorithms without using for loops? How depraved. No, I haven’t been without for loops. I had just assumed that the value of idx on the initial iteration of this loop was 0 instead of 1 because that is what it was read as. An assumption proved incorrect by moving the step into the body. After reading up more about for loops here, I learned what is actually happening is that the step is the last piece of the for loop to run.
2. A second step can be added to a for loop.
This one is simple enough. Each iteration will add an additional 1 to the num variable as well as increment the index of arr and add that index’s value to num. This results in num returning the sum of all numbers 1 through 10 (55) plus one for each iteration (10) for a total of 65.
I found out about this on a technical interview where I was required to refactor one of my solutions to use object lookup. This technique provides an easy way to map your array to an object using that array's index as your object's keys.
I find for..in and for…of to be neater syntax than a for loop that accomplishes the same task. For simple scenarios, I will fall back on these to make my code more readable, though it should be noted that they are not recommended compared to their iterative counterparts like forEach() or by simply looping. You can read more about for…in here and for…of here. One final point, take note of the differences between the output of for…in and for…of on the same array ‘holidays’. This has tripped me up in the past and is one of the reasons why alternatives are recommended.
I hope that by reading this article I am helping you to circumvent some of the same small pitfalls I wasted hours on (for…in v. for…of) and also provide some efficiencies for tasks you’ve already implemented (knowing how to efficiently implement object lookup in a function comes in handy).
As always, if you see any corrections I can make or suggestions you’d like to send my way, please reach out on LinkedIn, or in the comments. Thank you all for your time.