Javascript for loops with multiple conditions

Javascript for loops with multiple conditions

Create a Javascript for loop with multiple loop halting conditions


Usually when using for loops in Javascript, there is only ever a need for a single condition, say you want the loop to run 5 times starting from 1, you might use the following code:


for(var i=1;i<=5;i++){    
    
}    

This is fine for most situations in which a for loop is necessary, but some might not know you can have multiple conditions in a single for loop just like you would in an if statement for example.


Say you were looping over an array with an unknown amount of elements between 0 and 20, but you only wanted to loop over 5 of the elements at most, then you could use a condition like "i<arr.length && i<5" which will stop the loop if the loop variable "i" is no longer smaller than the array length or if "i" is no longer smaller than 5.


Example:


var guests = ["john", "bob", "marie"];    
var arrayLength = guests.length;    
    
for(var i=0;i<arrayLength && i<5;i++){    
 console.log(guests[i] + ", ");    
}    
//outputs "john, bob, marie"    
    
var guests = ["john", "bob", "marie", "chris", "barbara", "nick"];    
var arrayLength = guests.length;    
    
for(var i=0;i<arrayLength && i<5;i++){    
 console.log(guests[i] + ", ");    
}    
//outputs "john, bob, marie, chris, barbara"    

The above example shows 2 different loops with the same condition. The first loops over an array with a length of 3, because of the part of the condition "i<arrayLength" the loop will stop because "i" is no longer smaller than the array length.


The second loops over an array with a length of 6, now because of the part of the condition "i<5" the loop will stop while only having printed out 5 of the 6 elements because "i" is no longer smaller than 5.



Christopher Thornton@Instructobit 6 years ago
or