Learn JavaScript : Loops (Part 8)

JavaScript loops


A well-planned and executed loop can save you days of repeated tasks, a wrongfully executed loop can cause you loss of biological and machine resources. (Mark Anthony Graham)


Introduction

Loops in computer programming are like a set of instructions that can be repeated over and over again. They're like a helpful tool that programmers use to make their work easier. With loops, programmers can avoid doing the same task over and over manually.

Loops are important because they allow us to do things again and again until a specific condition is met. This is really useful when we need to work with a lot of data or when we have to solve a complex problem that requires multiple calculations.

The great thing about loops is that they save time and help us write shorter and more organized code. They do this by automating repetitive tasks. Instead of writing the same code again and again, we can write it once and tell the loop to do it multiple times. This makes our code more efficient and easier to manage.

Loops also give us control and flexibility. We can decide how many times we want the loop to repeat or when we want it to stop. We can even change the way the loop behaves based on different conditions. This makes it easier to handle different situations and make our code more adaptable.

Another interesting thing about loops is that they allow us to work with collections of data, like lists or arrays. We can go through each item in the collection and do something with it. This is really handy when we want to search for specific items, filter out some data, or sort things in a certain order.

In all, loops are like a helpful tool that allows programmers to automate repetitive tasks, work with lots of data, and write more efficient and organized code. They make our lives easier by saving time and giving us more control over our programs.


Let's look at the loop syntax


for loop:

   The for loop is widely used when you know the exact number of iterations required. It consists of three parts:

   - Initialization: It initializes a variable before the loop starts, typically used to set the initial value of a counter variable.

   - Condition: It defines the condition that must be true for the loop to continue executing. If the condition evaluates to `false`, the loop terminates.

   - Increment/Decrement: It updates the value of the counter variable after each iteration.


   Here's an example that prints the numbers 0 to 4:

-------------------------------------------------------------------------------------------------

javascript

   for (let i = 0; i < 5; i++) {

     console.log(i);

   }

-------------------------------------------------------------------------------------------------


   Output:


   0

   1

   2

   3

   4

   -------------------------------------------------------------------------------------------------


while loop:

   The while loop repeatedly executes a block of code as long as a specified condition is true. It consists of a single condition:


   - Condition: It is checked before each iteration. If the condition evaluates to `false`, the loop is terminated.


   Here's an example that prints the numbers 0 to 4 using a while loop:


-------------------------------------------------------------------------------------------------

 javascript

   let i = 0;

   while (i < 5) {

     console.log(i);

     i++;

   }

-------------------------------------------------------------------------------------------------


   //Output:

   

   0

   1

   2

   3

   4

   -------------------------------------------------------------------------------------------------


do-while loop:

   The do-while loop is similar to the while loop, but it guarantees that the block of code is executed at least once, regardless of the condition. It consists of a single condition:

   - Condition: It is checked after each iteration. If the condition evaluates to false, the loop is terminated.

   Here's an example that prints the numbers 0 to 4 using a do-while loop:


-------------------------------------------------------------------------------------------------

javascript

   let i = 0;

   do {

     console.log(i);

     i++;

   } while (i < 5);

   -------------------------------------------------------------------------------------------------


   //Output:

   

   0

   1

   2

   3

   4

   -------------------------------------------------------------------------------------------------


for...in loop:

   The for...in loop is used to iterate over the properties of an object. It iterates over each enumerable property in the object and executes a block of code for each property. It is often used when you need to perform operations on each property of an object.

   Here's an example that prints the properties and values of an object:


-------------------------------------------------------------------------------------------------

javascript

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

   for (let prop in obj) {

     console.log(prop + ': ' + obj[prop]);

   }

  -------------------------------------------------------------------------------------------------

   //Output:


   a: 1

   b: 2

   c: 3

-------------------------------------------------------------------------------------------------


   Note: The order of iteration in a `for...in` loop is not guaranteed and may vary between JavaScript engines.


for...of loop:

   The for...of loop is introduced in ECMAScript 6 (ES6) and is used to iterate over iterable objects. It provides a simpler syntax for iterating over arrays, strings, maps, sets, and other iterable objects.

   Here's an example that prints the elements of an array:


-------------------------------------------------------------------------------------------------

javascript

   const arr = [1, 2, 3];

  


 for (let value of arr) {

     console.log(value);

   }

-------------------------------------------------------------------------------------------------

   Output:

   1

   2

   3

-------------------------------------------------------------------------------------------------

   The for...of loop abstracts away the index-based iteration and allows you to directly access the values of the iterable.

Let's learn more on index-based iteration and for...of 

The for...of loop in JavaScript provides a simplified way to iterate over iterable objects, such as arrays, strings, maps, sets, and other collections. It allows you to directly access the values of the iterable without needing to manually manage indices or keep track of the iteration.

Traditionally, when iterating over an array or a similar data structure, you would use a for loop and access elements using their index. For example:


-------------------------------------------------------------------------------------------------

//javascript

const arr = [1, 2, 3];

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

  const element = arr[i];

  console.log(element);

}

-------------------------------------------------------------------------------------------------


In the above code, the loop uses an index `i` to access each element of the array arr. This index-based iteration requires you to explicitly use the index to retrieve the element.


However, the for...of loop simplifies this process by abstracting away the index. Instead of accessing elements by index, you can directly access the values of the iterable using a variable of your choice. Here's how you would achieve the same result with a for...of loop:


-------------------------------------------------------------------------------------------------

// javascript

const arr = [1, 2, 3];

for (const element of arr) {

  console.log(element);

}

-------------------------------------------------------------------------------------------------

In this case, the for...of loop automatically iterates over each element of the arr array, and the element variable represents the current value of the iteration. You don't need to manually manage the index or retrieve the value using an index-based approach.

The for...of loop provides a more intuitive and concise way to work with iterable objects, especially when you only need to access the values and don't require the index information. It simplifies the code and makes it more readable by focusing on the elements themselves rather than the mechanics of indexing.

Conclusions

Loops are valuable tools in programming. They automate tasks, enhance code speed and efficiency, and make working with data collections easier. By using loops, programmers can write code that is easier to handle, saves time, and boosts overall productivity.

HaPpY Coding😀

Comments

followers

Popular posts from this blog

The Beauty Of Using Flutter With Dart For Mobile Development

Building a Fortified Database Connection in PHP

Mastering Error Handling in PHP: A Deep Dive into `@` and `try...catch`