JavaScript allows you to iterate over arrays, objects, and other data structures making it easy to keep your code lean and DRY.
You don’t come to appreciate the beauty of JavaScript loops until you’re faced with large data sets or repetitive tasks.
In this guide, we’ll cover the four most commonly used types of JavaScript loops: for, for-in, for-of, and while.
We’ll go over the syntax and provide examples for each loop to help you understand how they work.
By the end of this post, you’ll have a solid understanding of how to use JavaScript loops to improve the efficiency and readability of your code.
1. for-loop
Syntax: for ( starting value; up to value; increment ) { . . . }
Example: for ( let i = 0; i ≤ 10; i++ ) { . . . }
let i = 0
: Starting variable with a value. (There’s no need for the variable to be called “i” or to equal “0”.)
Note: This could just as easily be
let myVar = 5
or you can go ahead and declare the variable outside the function and simply point to it. Typically though you have a variablei
that represents an index of an iterable element.
- Statement separator (
;
): Each for-loop statement needs to be separated by a semicolon. i++
: Shorthand fori = i + 1
which increases the value of variablei
by one with each loop (helping us avoid the case of an infinite loop).
Tip: Avoid infinite loops! Browsers will crash if you don’t handle the increment and/or conditional logic of your loop correctly.
Now let’s create a list to see a for loop in action:
const BTS = [
'Jung Kook',
'V',
'Jimin',
'SUGA',
'Jin',
'RM',
'j-hope'
];
Looping through the BTS list using a for loop looks like this:
for ( let i = 0; i < BTS.length; i++ ) {
console.log(i);
}
Our loop returns a list of indices each representative of an item in that list.
But we’re not limited to the indices of each list item. You can get the value of a particular index through BTS[i]
.
Note: The use of “
i
” is arbitrary – you’ll reference whatever it is you called your variable.
In the following example, I’m identifying my BTS bias (aka my favorite member from within the group) using a conditional statement. Here I know the value I’m looking for but not the index.
for ( let i = 0; i < BTS.length; i++ ) {
// Who's my BTS bias?
if ( BTS[i] === 'RM' ) {
console.log(`Item number ${i+1} on the list is my bias RM!!!`);
}
}
Tip 🤓
Wondering why the index isi + 1
instead of justi
? That’s because index count starts at zero but no one I know ever starts counting at zero (including myself) so adding one fixes that!
2. while-loop
Syntax: while ( condition ) { . . . }
Example: while ( i < 50 ) { . . . } // Assuming i is declared with a starting value
- A while loop will keep running as long as the provided condition is met
- It’s best to use it when you don’t know the definite number of iterations
- Increment variable
i
within the loop body or risk running an infinite loop - Use the
break
keyword to end the loop
Note: The
break
keyword is most commonly used in while-loops because of the indefinite iterations.
For a simple example of a while-loop in action, let’s go back to the BTS list.
The while-loop below will keep running as long as i <= 5
with each iteration rendering the item index and corresponding value.
If the value happens to be my bias, RM, then a slightly modified result is returned identifying him 🙂
let i = 0;
while ( i <= 5 ) {
console.log(`Item: ${i}, Name: ${BTS[i] === 'RM' ? `${BTS[i]} !!! MY BIAS !!!` : BTS[i]}`);
i++;
}
I’m using a template literal to inject JavaScript directly into a string and a ternary operator to perform conditional logic (aka
if (something happens) { do this } else { do that }
only shorter and cleaner).
Keep in mind this while-loop example is not complex.
While-loops, however, can be tricky to work with because of the ease with which you can fall into the infinite loop trap. Just remember incrementation and break
!
3. for…of loop
Syntax: for ( variable of iterable ) { . . . }
Example: for ( let item of myList ) { . . . }
let item
: Declares a variable called itemof
: Required keyword syntax of for…of loop that assigns each item in myList to the declared variablemyList
: An array, or another iterable element like a string, declared before the for…of loop
Tip: A for…of loop is good to use when you work with the values of an array and don’t need the index.
Back to the BTS list, let’s see how we can avoid referencing the value through the index by grabbing the name directly.
for( let member of BTS ) {
console.log(member === 'RM' ? `${member} !!! MY BIAS !!!` : member);
}
Keep in mind for…of loops don’t work with object literals (the term for JavaScript objects) because objects are not considered iterable.
As an example, let’s create an object representing BTS’s RM:
// Stats courtesy of https://kprofiles.com/bts-bangtan-boys-members-profile/
const myBias = {
stageName: 'RM (아르엠)',
birthName: 'Kim Nam Joon (김남준)',
position: 'Leader',
main: 'Rapper',
birthday: 'September 12, 1994',
zodiacSign: 'Virgo',
spotifyList: 'RM’s Favorite Tracks'
}
Looping through the object myBias produces the following console error message: Uncaught TypeError: myBias is not iterable
.
And if we check the length of myBias, console.log(myBias.length)
, we don’t get the number of properties in the object but an undefined
.
Despite JavaScript objects not having a predefined length, we can still use a for…of loop to loop over the keys or values of an object using either Object.keys(myObject)
or Object.values(myObject)
.
Either built-in method accepts an object as an argument and returns a list of keys or values based on which method was used. Since an array is an iterable element, the for…of loop works just fine 👍
console.log(Object.keys(myBias));
// Returns ["stageName", "birthName", "position", "main", "birthday", "zodiacSign", "spotifyList"]
console.log(Object.values(myBias));
// Returns ["RM (아르엠)", "Kim Nam Joon (김남준)", "Leader", "Rapper", "September 12, 1994", "Virgo", "RM’s Favorite Tracks"]
Tip: You can use 4. for…in loop
Syntax:
for ( variable in object ) { . . . }
Example:
for ( let key in myObject ) { . . . }
- Each loop returns the key of the provided object
- Access the value of the corresponding key using
myObject[key]
As an example of a for…in loop, let’s display the key-value pairs in the myBias object:
for( let key in myBias ) { console.log(`${key}: ${myBias[key]}`); }
Rule of Thumb: Use for…of loop when working with an array or string and for…in loop when dealing with an object.
That wraps up all you need to know to get going with JavaScript loops and start creating smart, efficient code.
More on JavaScript: How To Link Javascript To HTML, 3 Ways