During my time at my coding bootcamp, I learned and got pretty darn good at writing For loops. My understanding is that For loops iterate through an array and can perform an action on each element within the block of code. If I needed to hold onto a counter, or the index, of the element being iterated over, I would choose a For loop instead of a built-in method such as .map or .forEach. In Javascript, these loops look something like this:

let array = [1, 2 , 3, 4, 5]

These For loops are really common. In javascript though, a For loop written this way can be prone to a lot of errors and tiny mistakes. Usually typos! Such as typing a comma instead of a semi-colon, or starting the index at 0 when you actually need to start at 1. This way is seen as a more “manual” way to write for loops. Recently, I found there is another way to write for loops in javascript with the ES62015 update! If you don’t need to hold onto a counter or an index, this way is much easier.

let array = [1, 2 , 3, 4, 5]

So much easier and less prone to stupid mistakes. Basically, you are declaring the variable and then state the array you are iterating over. And that’s it!

Now, I also found out you can iterate over an object as well. With a For- In loop:

const object = { a: 1, b: 2, c: 3 };

Again, really simple. You declare the key variable you’re iterating over and then the name of the object. You can then reference both the key and the value like above.

Hope this helps writing for loops and getting rid of some errors during algorithm interview problems.