Mastering Dart Loop Structures: For, For-In, and ForEach Loops

Introduction and Overview

Welcome to our detailed analysis of Dart's loop structures, critical tools for automating iterative operations. We will delve into the intricacies of the For Loop, the For-In Loop, and the ForEach Loop. Let's get started!

Introduction to Dart `For` Loops

Dart's loops, akin to playing your favorite song on a loop, enable tasks to be executed repeatedly. Here's a simple for loop that prints numbers from 1 to 5:

for (var i = 1; i <= 5; i++) {
    print(i); // Prints numbers from 1 to 5
}
/*
Prints:
1
2
3
4
5
*/

Our for loop starts by declaring i as 1, checks the condition i <= 5, and increment i by 1 in each cycle using i++. As a result, i moves from 1 to 5, printing the current value of i in each cycle.

Note: i++ is an increment operation that increases the value of i by 1. It's equivalent to i = i + 1 or i += 1, but in a more compact form.

Deep Dive into `For` Loop

Let's revisit our example:

for (var i = 1; i <= 5; i++) {
    print(i); // Will print numbers from 1 to 5
}

The For Loop comprises three components:

  • Initialization: Here, i begins with a value of 1.
  • Condition: The loop continues as long as i <= 5 holds true.
  • Changes: In this instance, i++ increases i by 1 with each successive loop iteration.
    • The changes can be modified as per the requirements; for example, we could also decrement i by 1 if the situation demands.

The general structure of the loop is as follows:

for ([initialization]; [condition]; [changes]) {
    [loop body]
}

For instance, consider this snippet that lists all seven days of the week:

var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for (var i = 0; i < days.length; i++) { // 'i' traverses all indexes in 'days' 
    print(days[i]); // Prints each day of the week
}
/*
Prints:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
*/

Exploring `For-In` Loop

The For-In loop iterates over items in a collection such as a list or a set:

var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for (var day in days) {
    print(day); // Prints each day of the week
}
/*
Prints:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
*/

In this case, the variable day loops over each element in the days, enabling us to print each day of the week.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal