Loops in JavaScript
Loops are like a shortcut in programming. They let you do the same thing over and over without writing a bunch of repetitive code. Think of them as a way to automate tasks, like checking each item in a list or running a command multiple times. In this section, we’ll explore the most common loops in JavaScript: for
, while
, and do...while
.
for Loop
The for
loop is like a recipe for repetition. It tells your program where to start, when to stop, and how to move forward.
Syntax:
for (start; stop condition; step) { // What you want to do each time }
- Start: Set up a starting point. Usually, this is where you set a counter.
- Stop condition: The loop keeps going as long as this condition is true.
- Step: How you move forward in the loop, often by increasing the counter.
It might make more sense if we use a real example:
for (let i = 0; i < 5; i++) { console.log("Iteration number:", i); }
In this example, i
starts at 0. The loop runs as long as i
is less than 5, and i++
means we add 1 to i
after each loop. This prints "Iteration number:" followed by the current number five times.
while Loop
The while
loop is more flexible. It keeps running as long as a certain condition is true, which is great when you don't know in advance how many times you need to repeat something.
Syntax:
while (condition) { // What you want to do while the condition is true }
And again, let's look at example of it in action:
let count = 0; while (count < 5) { console.log("Count is:", count); count++; }
Here, count
starts at 0
. The loop runs as long as count
is less than 5. It prints "Count is:" and the current number each time, then adds 1
to count
.
Looping Through Strings and Arrays
Loops are fantastic for working with strings (text) and arrays (lists of items). You can use them to go through each character in a string or each item in an array.
Looping Through Strings
Let's loop over some text and log each character:
let name = "JavaScript"; for (let i = 0; i < name.length; i++) { console.log("Character at index", i, "is", name[i]); }
In this example, the loop goes through each character in the string name
and prints out the character along with its position (index).
Looping Through Arrays
And in a very similar fashion, we can do the same with arrays:
let fruits = ["apple", "banana", "cherry"]; for (let i = 0; i < fruits.length; i++) { console.log("I like", fruits[i]); }
Here, the loop goes through each item in the fruits
array and prints "I like" followed by the fruit's name.
Breaking Out of Loops
Sometimes, you might want to stop a loop before it finishes. The break
statement is like a stop sign—it halts the loop right away.
Here's how you add it:
for (let i = 0; i < 10; i++) { if (i === 3) { break; // Stop the loop when i is 3 } console.log(i); }
In this example, the loop will print numbers from 0 to 2. When i
reaches 3, the break
statement stops the loop.
Skipping to the Next Loop Iteration
The continue
statement is helpful when you want to skip the rest of the code inside the loop for the current round and jump straight to the next one.
Here's how you use it:
for (let i = 0; i < 5; i++) { if (i === 2) { continue; // Skip the rest of the loop when i is 2 } console.log(i); }
In this example, the loop will print numbers from 0
to 4
, but it will skip printing the number 2.
Dynamic Loops
Dynamic loops are super cool because they let you do things based on changing conditions, like the length of an array or a string.
This means you can write one loop that will work for arrays or strings of any size (without knowing the size ahead of time). Let's examine an example where we use a loop to process each item in an array and another where we manipulate each character in a string.
Looping Based on Array Length
When working with arrays, you often want to do something with each element. But what if you don't know how many elements there are?
That's where the array's length
property comes in handy. You can use it to make your loop dynamic and flexible, handling arrays of any size.
Example: Uppercasing and Lowercasing Alternating Array Elements
Let's say you have an array of words and want to capitalize every second word while lowercase the others.
const words = ["apPle", "BANaNA", "Cherry", "daTE", "Elderberry", "fIg"]; for (let i = 0; i < words.length; i++) { if (i % 2 === 0) { // Lowercase the letter words[i] = words[i].toLowerCase(); } else { // Uppercase the letter words[i] = words[i].toUpperCase(); } } console.log(words); // Output: ['apple', 'BANANA', 'cherry', 'DATE', 'elderberry', 'FIG']
In this example, i % 2 === 0
checks if the index i
is even. If it is, the word is converted to lowercase. If it's odd, the word is converted to uppercase. This way, the loop works no matter how long the words
array is.
Looping Based on String Length
We can basically do the same thing to manipulate strings.
For example, you might want to uppercase every second character and lowercase the others.
Example: Alternating Uppercase and Lowercase Characters in a String
const phrase = "JavaScript is Fun!"; let newPhrase = ""; for (let i = 0; i < phrase.length; i++) { if (i % 2 === 0) { newPhrase += phrase[i].toUpperCase(); } else { newPhrase += phrase[i].toLowerCase(); } } console.log(newPhrase);
In this example, phrase[i]
gets each character in the string. The loop goes through each character in the phrase
string. If the index i
is even (i % 2 === 0
), the character is made uppercase and added to newPhrase
. If the index is odd, the character is made lowercase.
Whether you're working with arrays, strings, or other data structures, you can make your code adapt to whatever it encounters. This makes your programs more flexible and powerful, as they can handle many inputs without needing a rewrite.
Key Takeaways:
- Use
array.length
to control your loop based on the size of an array. - Use
string.length
to work with each character in a string. - Combine loops with conditionals to perform complex operations on each element or character.
Keep experimenting with these concepts to get a feel for how powerful and versatile loops can be in your JavaScript projects!