JavaScript is a powerful programming language that offers various constructs to help developers solve complex problems efficiently. One such construct is the "for loop," which allows you to repeat a block of code multiple times. In this article, we'll explore the ins and outs of JavaScript for loops, providing clear explanations and practical examples along the way.
A for loop is a control flow statement that repeatedly executes a block of code until a specified condition is met. It consists of three main components:
The general syntax of a for loop looks like this:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Let's start with a simple example to demonstrate how a for loop works. Suppose we want to print numbers from 1 to 5. We can achieve this using a for loop as follows:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output
1
2
3
4
5
Explanation:
A common use case for for loops is to iterate over arrays. Let's say we have an array of fruits, and we want to print each fruit's name. Here's how we can accomplish that:
const fruits = ['apple', 'banana', 'orange', 'grape'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output
apple
banana
orange
grape
Explanation:
In JavaScript, objects are not iterable by default. However, we can loop through the keys of an object using a for...in loop. Here's an example:
const person = {
name: 'John',
age: 30,
profession: 'developer'
};
for (let key in person) {
console.log(key + ':', person[key]);
}
Output
name: John
age: 30
profession: developer
Explanation
Sometimes, you may need to perform nested iterations. This can be achieved by using multiple for loops. Let's say we want to print a pattern of asterisks. Here's how we can accomplish that:
for (let i = 1; i <= 5; i++) {
let pattern = '';
for (let j = 1; j <= i; j++) {
pattern += '*';
}
console.log(pattern);
}
Output
*
**
***
****
*****
Explanation:
You can control the flow within a for loop using the break and continue statements. The break statement terminates the loop, while the continue statement skips the current iteration and moves to the next one. Let's see an example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
if (i === 4) {
break;
}
}
Output
1
2
4
Explanation:
Problem 1: Print even numbers between 1 and 10.
for (let i = 2; i <= 10; i += 2) {
console.log(i);
}
Output
2
4
6
8
10
Problem 2: Calculate the sum of numbers between 1 and 5.
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i;
}
console.log(sum);
Output
15
In this article, we covered the fundamentals of JavaScript for loops. We learned how to use for loops for basic iterations, looping through arrays and objects, nesting loops, and controlling the loop flow. By practicing and experimenting with for loops, you'll gain a solid understanding of their versatility and be able to solve a wide range of programming problems.
51 videos|28 docs|12 tests
|
|
Explore Courses for Software Development exam
|