JS for loop is crucial to programming as it involves doing the same thing repeatedly, also known as iteration. Using the for loop usually involves several features, which can include a few things:
- A counter: The value that tells the loop where and when to start.
- An iterator: Determines how often the counter moves in increments.
In any for loop, you want to ensure you have incremented or decremented the initializer so it can reach the condition to exit. If you do not allow the loop to reach the exit condition, then the loop can keep going forever — or until your browser crashes.
For example, if you want to search an array that contains telephone numbers, your code would look something like this:
To run this type of loop, use zero to start your counter and run it until it is equal to or greater than the contacts.length. You can then increment by one after each of the loop’s iterations. Splitting the contact allows you to store these values as splitContact. You can plug in your conditional statement to determine whether the name of the contact equaled the search. If so, you can place a string in your paragraph to say what the number of the contact and end the loop with “break.”