JavaScript For Loop | JavaScript for Web Development - Software Development PDF Download

Introduction

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.

What is a for loop?

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:

  • Initialization: The loop counter is initialized with an initial value.
  • Condition: The loop continues as long as the condition evaluates to true.
  • Increment/Decrement: The loop counter is incremented or decremented after each iteration.

Anatomy of a for loop

The general syntax of a for loop looks like this:

for (initialization; condition; increment/decrement) {

  // code to be executed

}

Basic for loop example

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:

  • Initialization: We initialize the variable i with the value 1.
  • Condition: The loop continues as long as i is less than or equal to 5.
  • Increment: After each iteration, the value of i is incremented by 1.
  • Console Output: The value of i is printed to the console.

Looping through an array

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:

  • Initialization: We initialize the variable i with the value 0 since array indices start from 0.
  • Condition: The loop continues as long as i is less than the length of the fruits array.
  • Increment: After each iteration, the value of i is incremented by 1.
  • Console Output: The value of fruits[i] is printed to the console.

Looping through an object

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

  • Initialization: We declare the variable key to represent each key in the person object.
  • Condition: The loop iterates over each enumerable key in the person object.
  • Console Output: The key and its corresponding value are printed to the console.

Nesting for loops

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:

  • Outer Loop: Iterates from 1 to 5 to control the number of rows.
  • Inner Loop: Iterates from 1 to the current row number to control the number of asterisks in each row.
  • Console Output: The pattern of asterisks is printed to the console.

Control flow within a for loop

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:

  • The continue statement skips the iteration when i is equal to 3.
  • The break statement terminates the loop when i is equal to 4.

Sample Problems

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

Conclusion

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.

The document JavaScript For Loop | JavaScript for Web Development - Software Development is a part of the Software Development Course JavaScript for Web Development.
All you need of Software Development at this link: Software Development
51 videos|28 docs|12 tests

Top Courses for Software Development

51 videos|28 docs|12 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

pdf

,

past year papers

,

Summary

,

JavaScript For Loop | JavaScript for Web Development - Software Development

,

JavaScript For Loop | JavaScript for Web Development - Software Development

,

JavaScript For Loop | JavaScript for Web Development - Software Development

,

Exam

,

Semester Notes

,

study material

,

practice quizzes

,

Viva Questions

,

video lectures

,

Free

,

mock tests for examination

,

Extra Questions

,

ppt

,

MCQs

,

Sample Paper

,

Important questions

,

Objective type Questions

,

shortcuts and tricks

,

Previous Year Questions with Solutions

;