Using for Loops

Ronan McClorey
2 min readOct 23, 2020

--

There are different types of loops available to use in JavaScript one of the most common loops is a for loop.

Photo by Tine Ivanič on Unsplash

For loops can be extremely useful in solving coding and algorithm problems you might see on sites like leetcode or hackerrank or they can be used in coding interview questions.(However note they are are often more efficient methods with regards to Big O than just a for loop for several of these problems.)

How they work? For loops will continue to repeat (loop over itself) until the inserted statement evaluates to false, this is true for a standard for loop. There is also ‘for…in’ loops and ‘for…of’ loops which can simplify your code if your loop is intended to loop through an entire string, array or object for example.

For loops can be used to solve complex algorithmic problems but just to illustrate an example of how they can be used, as well as how a for loop can be made into a for…of loop I will use a simple example. For this example I will simply write a function that reverses an inputed string

function reverse(str) {
let reversed = ''
for(let i = 0; i < str.length; i++) {
reversed = str[i] + reversed
}
return reversed
}

This loop runs through the string starting at index 0 of the string and adds each letter to the new variable reversed, to reverse the string and return the new reversed string. This same loop can be written as a for…of loop as shown below:

function reverse(str) {
let reversed = ''
for(let character of str) {
reversed = character + reversed
}
return reversed
}

In this for…of loop the entire string is iterated through the same as above to give us a reversed string. Both loops achieve the same outcome, the for…of loop however has a simpler code for iterating through the string.

The MDN web docs explain the for … of statement with examples here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

--

--

No responses yet