Learning JavaScript
- Part 1: Creating and Using Variables
- Part 2: Data Types and Arrays
- Part 3: Functions
- Part 4: Objects
- Part 5: Document Object Model
- Part 6: Conditional Statements
- Part 7: Loops
JavaScript is an interpreted programming language commonly found in web browsers. First appearing in 1995, it has grown to be the de facto web programming language used in most websites and on many systems serving webpages.
Loops
One of the most common programming concepts that nearly all languages share is that of loops or looping. Some languages call the concept different names and have certain functionality to achieve it, but it exists as a nearly universally used concept.
In JavaScript, there are two main forms of loops: while and for.
While Loops
Similar to conditional statements, a while loop runs any code found within it over and over again until the condition is no longer true.
For Loops
A for statement is made up of four parts run in order:
- Initial statement
- Condition to check before each loop
- Code inside the loop
- Statement to run after each loop
For statements are the most commonly used in situations where the loop will have a fixed or known number of cycles. The initial statement, then, is often set to 0 or another value and acts as the counter for the number of loops.
The condition is what keeps the loop running. For as long as the condition holds true, the for statement will run. As soon as it is no longer true, the looping breaks.
Frequently, the last statement within the for statement will increase the counter created in the initial statement. In most cases, this will be a “++” increment or “–” decrement operator that works as a short hand to increase or decrease the value by 1 each time.
For Loops and Arrays
One of the more common use cases for a for loop is with an array or other data structure where the length is known. Using a for loop to move through an array is easy because the variable used to control the loop can be used as the index to the array.
Because array positions start with 0, a for loop’s variable can also be set at 0 and increase by one per loop. As long as it is less than the length of the array, it will go through all of the values one by one.
For-In Loops
JavaScript also allows for using a for loop using a for…in pattern. Instead of using a number for the control of the loop, it will run by setting some variable to the next value within it until there are no more available values.
The for…in pattern is the most useful for objects. Because objects have properties and not indexes where data can be found, the for…in loop can use the name of the property itself as an index to find a value.
Codepen Example:
See the Pen Learning JavaScript: Part 7: Loops by Dan Cox (@videlais) on CodePen.