Still Don't Understand Loops? Look No Further.

jhaemishack

Jhaemis-hack

Posted on November 26, 2024

Still Don't Understand Loops? Look No Further.

In this post, I will be addressing all you concerns about what loops are and how they work. Whichever programming language you are currently learning, whether it is Java, Python, JavaScript, C#, c++, e.t.c, they all follow the same nomenclature of action. I intend to help you trash out the concept of Loops on your Journey to becoming a programmer. In this post, I will make use of JavaScript as a reference point to whichever Language you are learning.

What is a Loop?

According to Zuckerberg's Chat Bot(Meta AI): A loop is a control structure in programming that allows a sequence of instructions to be executed repeatedly, either for a fixed number of iterations or until a specific condition is satisfied.

I like this definition as it makes explicit indication - "Until a specific condition is satisfied". To redefine it, Loops are blocks of code that will not stop iterating over and over unless an already declared condition becomes false (i.e, condition is no longer true).

When constructing a loop, a condition of action is always declared and the loop will not be terminated unless the declared condition is no longer true.

There are basically, 2 major types of Loops in all programming languages:

  1. For Loop
  2. While Loop

However, In JavaScript there are 5 forms of Loops:

  1. For Loop
  2. For Of Loop
  3. For In Loop
  4. While Loop
  5. Do While Loop

I will focus on those 2 major ones in this post while also making references to the other forms we have in Javascript.

FOR LOOP

As I have already established, Loops are used for repeatedly running some blocks of code. However, they all have their best used cases. FOR loops are mostly used to iterate over a sequence, such as an array, object, set, or string.

If you want to individually work with all the members of an array or object, For Loop might just be your best choice.

Here is a simple structure of a For Loop

// Define an array

let numbers = [1, 2, 3, 4, 5];

// Use a For loop to iterate over the array

for(let i = 0; i < numbers.length; i++) {

  // Print each number

  console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

We define an array numbers containing five integers.
The For loop iterates over the numbers array.
The variable i is the loop counter, initialized to 0.
The loop condition checks if i is less than the length of the numbers array which is 5.
Inside the loop, we print the current value of numbers[i] using console.log()
Immediately i becomes > than numbers.length, it becomes false and terminates the Loop

The same is also the case if it is an arrays of strings. However, when working with arrays of strings, it is most advisable to make use of FOR OF loop.

const myArray = ["lucy", "lumzy", "rex", "apex", "wixy"];

for (const item of myArray) {
    console.log(item);
}

Enter fullscreen mode Exit fullscreen mode

This will print each element of myArray to the console.
the itemis standing as an index representator for all the element in myAarray, beginning from the first to the last

And if it is an Object, it's best to make use of a FOR IN Loop.

const myObject = { a: 1, b: 2, c: 3 };

for (const key in myObject) {
    console.log(`Key: ${key}, Value: ${myObject[key]}`);
}

Enter fullscreen mode Exit fullscreen mode

The for...in loop iterates over the keys of the myObject.
The variable key holds the current key or property (e.g., a, b, c).
The value of the current key is accessed using myObject[key].

In JavaScript, a for...in loop is used to iterate over the keys (or properties) of an object. Reference can also be made to the values using the keys.

Take your time to read through the For Loop below to better understand how it works.

// Define an object

let students = [
  { name: 'John Doe', age: 20, grade: 85 },
  { name: 'Jane Doe', age: 22, grade: 90 },
  { name: 'Bob Smith', age: 21, grade: 78 },
  { name: 'Alice Johnson', age: 20, grade: 92 },
];

// Use a For loop to iterate over the array

for (let i = 0; i < students.length; i++) {
  // Check if the student's grade is above 85 and age is above 21

  if (students[i].grade > 85 && students[i].age > 21) {
    // Print the student's name and grade

    console.log(`${students[i].name} has a grade of ${students[i].grade}`);

  } else if (students[i].grade > 85 && students[i].age <= 21) {
    // Print a message if the student's grade is above 85 but age is 21 or below

    console.log(`${students[i].name} is a high-achieving student, but not yet 22 years old.`);

  } else {
    // Print a message if the student's grade is 85 or below

    console.log(`${students[i].name} needs to improve their grade.`);
  }
}

Enter fullscreen mode Exit fullscreen mode

WHILE LOOP

While loop is less preferred by most programmers due to its unique conditional cases. Unlike For loop, While Loops can both be used with a Boolean and numeric conditional cases.

// Initialize a counter variable

let i = 0;

// Set a condition for the loop

while (i < 5) {

  console.log(`Counter: ${i}`)// Print the current value of the counter

  i++;
}
Enter fullscreen mode Exit fullscreen mode

Using a Boolean test case as conditions allows programmers a lot of unique usage of the Loop.

Here is a simple code block for a while loop:

let count = 0;

while (count < 5) {
    console.log(`Count is: ${count}`);

    count++; // Increment the count
}

Enter fullscreen mode Exit fullscreen mode

The loop continues as long as the value of count is less than 5.
count++; Increases the value of count by 1 on each iteration.
When count reaches 5, the condition count < 5 becomes false, and the loop stops.

However, While loop also works well with a Boolean Conditional case. Here is an example of such:

let isRunning = true;

while (isRunning) {
    console.log("The loop is running...");

    isRunning = false; // Change the condition to stop the loop
}

Enter fullscreen mode Exit fullscreen mode

After the first iteration, isRunning is set to false, so the loop condition is no longer satisfied, and the loop ends.

Similar to While loop is do-While loop. The only difference between the two is that While Loop condition is checked before the loop executes (i.e, the loop body may not run if the condition is false initially - "Check first, then execute"), whilest, Do-While Loop executes at least once before the condition is checked, regardless of whether the condition is true or false.

Here is a simple do-While Loop code:

let count = 0;

do {
    console.log(`Count is: ${count}`);
    count++;
} while (count < 5);

Enter fullscreen mode Exit fullscreen mode

Check up this While loop to better understand how it works in application.

let isLoggedIn = false;

// Simulate user login attempt

while (!isLoggedIn) {

  let username = prompt("Enter your username:");
  let password = prompt("Enter your password:");

  // Verify login credentials 

  if (username === "admin" && password === "password") {
    isLoggedIn = true; //sets the condition true

    console.log("Login successful!");

  } else {

    console.log("Invalid username or password. Please 
try again.");

  }
}

// User is now logged in

console.log("Welcome to the dashboard!");

Enter fullscreen mode Exit fullscreen mode

a boolean variable isLoggedIn is initialized to false.
The While loop checks the condition !isLoggedIn, which is equivalent to (isLoggedIn === false).
If the condition is true, the loop body executes
If the credentials are valid, sets isLoggedIn to true.
Steps 2-3 repeat until the condition !isLoggedIn is false.
Once the condition is false, the loop exits, and the user is logged in.

One common mistake programmers make with WHILE Loops is that they define the condition within the loop, which eventually crashes the terminal.

If you have followed me through up to this point, congratulations you have just divulged the most important points you need to know before effectively using a Loop.

💖 💪 🙅 🚩
jhaemishack
Jhaemis-hack

Posted on November 26, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related