Blog Blog Posts Business Management Process Analysis

How to Use For Loop in React? (With Examples)

Before diving into the exciting world of using for loops in React, it’s important to have a solid foundation in React development. Familiarity with JavaScript, including understanding concepts like arrays and functions, is crucial. 

Additionally, a working knowledge of JSX syntax and React components is essential. If you’re new to React, consider exploring introductory tutorials and gaining hands-on experience with React basics. Armed with these prerequisites, you’ll be well-prepared to unlock the true potential of for loops in your React applications.

Check out our Full Stack Web Development Course on YouTube:

{
“@context”: “https://schema.org”,
“@type”: “VideoObject”,
“name”: “Full Stack Web Development Course | Full Stack Developer Course | Intellipaat”,
“description”: “How to Use For Loop in React? (With Examples)”,
“thumbnailUrl”: “https://img.youtube.com/vi/ofekyjYd0xM/hqdefault.jpg”,
“uploadDate”: “2023-07-12T08:00:00+08:00”,
“publisher”: {
“@type”: “Organization”,
“name”: “Intellipaat Software Solutions Pvt Ltd”,
“logo”: {
“@type”: “ImageObject”,
“url”: “https://intellipaat.com/blog/wp-content/themes/intellipaat-blog-new/images/logo.png”,
“width”: 124,
“height”: 43
}
},
“embedUrl”: “https://www.youtube.com/embed/ofekyjYd0xM”
}

Introduction to Looping in Programming

Introduction to Looping in Programming

In the vast programming landscape, loops and iteration statements are essential tools that enable developers to perform repetitive tasks efficiently. When faced with scenarios where the same instructions must be executed multiple times, loops come to the rescue.

The concept behind loops revolves around the idea of iterating over a block of code until a certain condition is met. This iterative process allows for efficient execution and manipulation of data, saving developers from the burden of manually repeating the same set of instructions.

There are various types of loops available in most programming languages, including for loops, while loops, and do-while loops. Each loop type serves a specific purpose, catering to different scenarios and conditions.

The syntax of loops typically follows a similar structure across programming languages.

Below is the syntax of “for” loop:

for (initialization; condition; increment/decrement) {
    // code to be executed
}

The algorithm of a loop can be summarized as follows:

Loops empower programmers to handle tasks such as iterating through arrays, performing calculations on data sets, or even controlling the flow of a program based on specific conditions. By leveraging loops, developers can write concise and efficient code, enhancing productivity and reducing redundancy.

Whether it’s iterating through data structures or automating repetitive tasks, mastering the art of loops opens doors to endless possibilities and unleashes the true potential of software development.

Types of Loops in JavaScript

Let us explore the various types of loops in javascript that are as follows:

Types of Loops in JavaScript

The “for” Loop 

The “for” loop is widely used and allows you to repeat a code block for a specific number of times. Its syntax consists of an initialization statement, a condition, and an increment statement. 

Here’s an example:

for (let i = 0; i < 5; i++) {
  // Code to be repeated
}

Algorithm:

The “while” Loop 

The while loop repeatedly executes a block of code until a specified condition is true. Its syntax involves a condition that is evaluated before each iteration. Here’s an example:

let i = 0;
while (i < 5) {
  // Code to be repeated
  i++;
}

Algorithm:

The “do-while” Loop

The working of the do-while loop is similar to the while loop, the do-while loop executes a code block as long as the specified condition is true. However, the condition is evaluated after executing the code block, ensuring that the code executes at least once. 

Here’s an example:

let i = 0;
do {
  // Code to be repeated
  i++;
} while (i < 5);

Algorithm:

Coding Examples

Let’s see practical examples of loops in action:

Example 1: 

Printing numbers from 1 to 5 using a “for” loop.

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Output:

1
2
3
4
5

Example 2:

Summing numbers from 1 to 10 using a while loop.

let i = 1;
let sum = 0;
while (i <= 10) {
  sum += i;
  i++;
}
console.log(sum);

Output:

55

Example 3: 

Finding the factorial of a number using a do-while loop.

let num = 5;
let factorial = 1;
let i = 1;
do {
  factorial *= i;
  i++;
} while (i <= num);
console.log(factorial);

Output:

120

Become an expert in React by enrolling to our React JS Course.

Working of For Loop in React

Let’s start with a beginner-level example where we will use a “for” loop to render a list of elements in React.

import React from 'react';
function ListExample() {
  const fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
  const renderList = () => {
    const listItems = [];
    for (let i = 0; i < fruits.length; i++) {
      listItems.push(
  • {fruits[i]}
  • );
        }     return listItems;   };   return
      {renderList()}
    ;
    } export default ListExample;

    In the provided code illustration, we initiate the process by establishing an array containing various fruits, with the intention of presenting them individually as separate items within a list. Our initial step entails creating an empty array named “listItems“. Subsequently, through the utilization of a “for” loop, we iterate over each fruit within the array, generating an

  • element for each fruit and subsequently appending it to the “listItems” array. Finally, we present the resulting array of list items encapsulated within an
      element.
  • Now, let us delve into a more sophisticated scenario that involves employing a “for” loop to filter data based on a specific condition.

    import React from 'react';
    function FilterExample() {
      const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      const filteredNumbers = [];
      const filterData = () => {
        for (let i = 0; i < numbers.length; i++) {
          if (numbers[i] % 2 === 0) {
            filteredNumbers.push(numbers[i]);
          }
        }
      };
      filterData();
      return
    {filteredNumbers.join(', ')}
    ;

    }
    export default FilterExample;

    In the above coding example, we have used an array of numbers, and the aim is to filter out the even numbers. We initialize an empty array called filteredNumbers. Using a “for” loop, we iterate over the numbers array, and if a number is divisible by 2 (i.e., it’s even), we push it into the filteredNumbers array. Finally, we render the filtered numbers joined by commas.

    Types of For Loops in React

    Types of For Loops in React

    For/in Loop

    In React, the “for/in” loop is a handy construct that allows you to iterate over the properties of an object. Also, on the elements of an array. This loop provides an efficient way to access and manipulate data in React components. 

    Syntax of the "for/in" Loop:

    The syntax of the “for/in” loop in React is as follows:

    for (variable in object) {
      // Code to be executed for each property/element
    }

    The “variable” represents a different property or element on each iteration, while the “object” is the object or array you want to loop through.

    Code Example and Explanation:

    Let’s turn our gaze to a code example to understand how the “for/in” loop works in React:

    import React from 'react';
    function LoopExample() {
      const user = {
        name: 'John Doe',
        age: 25,
        email: 'johndoe@example.com',
        occupation: 'Developer',
      };
      const renderUserDetails = () => {
        const userDetails = [];
        for (const key in user) {
          userDetails.push(
            

              {key}: {user[key]}         

          );     }     return userDetails;   };   return
    {renderUserDetails()}
    ; } export default LoopExample;

    In the provided illustration, an object named “user” is presented, encompassing properties such as name, age, email, and occupation. To depict this, a function named “renderUserDetails” is established, initializing an empty array named “userDetails“. Employing the “for/in” loop, we systematically iterate through each property of the “user” object. For every property encountered, a paragraph element is generated, comprising the property name as a label and its associated value. In order to maintain uniqueness, a distinctive key is assigned to each paragraph element using the property name. Ultimately, the “userDetails” array is returned.

    Applications of the “for/in” Loop in React:

    For/of Loop

    The “for/of” loop in React is a powerful construct that allows you to iterate over iterable objects, such as arrays or strings. It provides a concise and elegant way to access and process each element of the iterable.

    Syntax of the “for/of” Loop:

    The syntax of the “for/of” loop in React is as follows:

    for (variable of iterable) {
      // Code to be executed for each element
    }

    The “variable” represents a different element on each iteration, while the “iterable” is the array or iterable object you want to loop through.

    Code Example and Explanation:

    Here, look at the coding example to understand how the “for/of” loop works in React:

    import React from 'react';
    function LoopExample() {
      const fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
      const renderFruits = () => {
        const fruitList = [];
        for (const fruit of fruits) {
          fruitList.push(
  • {fruit}
  • );

        }
        return
      {fruitList}
    ;

      };
      return
    {renderFruits()}
    ;

    }
    export default LoopExample;

    We have an array called “fruits” that contains different fruit names. We define a function called “renderFruits” that initializes an empty array called “fruitList“. Using the “for/of” loop, we iterate through each element of the “fruits” array. For each fruit, we create a list item element with the fruit name as the content. We assign a unique key to each list item element using the fruit name. Finally, we return the “fruitList” array wrapped in a

    Blog: Intellipaat - Blog

    Leave a Comment

    Get the BPI Web Feed

    Using the HTML code below, you can display this Business Process Incubator page content with the current filter and sorting inside your web site for FREE.

    Copy/Paste this code in your website html code:

    <iframe src="https://www.businessprocessincubator.com/content/how-to-use-for-loop-in-react-with-examples/?feed=html" frameborder="0" scrolling="auto" width="100%" height="700">

    Customizing your BPI Web Feed

    You can click on the Get the BPI Web Feed link on any of our page to create the best possible feed for your site. Here are a few tips to customize your BPI Web Feed.

    Customizing the Content Filter
    On any page, you can add filter criteria using the MORE FILTERS interface:

    Customizing the Content Filter

    Customizing the Content Sorting
    Clicking on the sorting options will also change the way your BPI Web Feed will be ordered on your site:

    Get the BPI Web Feed

    Some integration examples

    BPMN.org

    XPDL.org

    ×