Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

7 Loops

1 Intro To Loops

Imagine a scenario where you're required to print the statement "Hello World" a hundred times. Writing a print statement a hundred times can be tedious. What if you could achieve the same outcome with just a few lines of code? That's where loops come in handy, enabling us to write concise code for repetitive tasks.

Loops serve as fundamental control structures in programming languages, enabling you to execute a block of code repeatedly based on a specified condition. They streamline tasks such as printing messages multiple times, iterating through data collections, and performing repetitive operations efficiently.

Imagine needing to print a message a thousand times. Instead of writing one thousand console.log statements, you can use loops to achieve this more elegantly.

Many programming languages offer various types of loops, including:

  • For Loop
  • While Loop
  • Do While Loop

Here's a basic structure for a FOR loop:

for (variableInitialization; condition; incrementOrDecrement) {
    console.log("Message");
}

A FOR loop comprises three parts:

Variable Initialization

It's similar to declaring and assigning a value to a variable.

for (var i = 1; condition; incrementOrDecrement)

Condition

It represents the condition that determines whether the loop continues or terminates. For instance, if you want the loop to print "Hello World" 10 times:

for (var i = 1; i <= 10; incrementOrDecrement)

With each iteration, it checks whether the condition is true. When the condition is false, it terminates the loop.

Increment or Decrement:

It defines how the loop variable is updated with each iteration. This could be achieved using increment or decrement operators. For example:

for (var i = 1; condition; incrementOrDecrement)

Increment Operator: If we want to add 1 to i, we can express it as i = i + 1. An easier and more concise way to achieve the same result is by using i++.

Decrement Operator: If we want to subtract 1 from i, we can write it as i = i - 1. Similarly, a shorter notation for this operation is i--.

Examples

Printing "Hello World" 100 times

for (var i = 1; i <= 100; i++) {
    console.log("Hello World!");
}

This will print the Hello World message 100 times.

Printing 1-10 numbers with a For Loop

for (var i = 1; i <= 10; i++) {
    console.log(i);
}

Printing 1-10 numbers in Reverse Order

for (var i = 10; i > 0; i--) {
    console.log(i);
}

Iterating Arrays using a For Loop

let array = [1, 2, 9, 3, 43, 35, 5, 6];

// Get the length of the array
let arrayLength = array.length;

for (var i = 0; i < arrayLength; i++) {
    // Print the value of the array element at index i
    console.log(array[i]);
}

This loop iterates through each element of the array and prints its value.