DEV Community

Md Abdur Razzak
Md Abdur Razzak

Posted on

Loops in JavaScript !!πŸ“šπŸ”„

What is Loop in JavaScript ?

Ans: Basically loop use for do repeatedly run a block of code - until a certain condition is met.

Types of Loops

For Loop

  • When to Use: When you know how many times you want to repeat something.

  • How It Works: You start with a counter, repeat code as long as the counter is less than a limit, and update the counter each time.

  • Example:

Image description

while Loop

  • When To use: When you don't know exactly how many times you need to repeat something, but you have a condition to check

  • *How It Works: *

  1. The condition is checked.

  2. If the condition is true, the code inside the loop is executed.

  3. The condition is checked again.

  4. Steps 2 and 3 repeat until the condition becomes false.

  • Example:

Image description

Do-While Loop

  • When To use: Similar to a while loop, but the code inside the loop always runs at least once.

  • *How It Works: *

  1. The code inside the do block is executed once before any condition is checked.

  2. After executing the code block, the while condition is evaluated.

  3. If the condition evaluates to true, the loop executes the code block again. If the condition evaluates to false, the loop terminates, and the program continues with the code that follows the loop.

  • Example:

Image description

For In Loop

  • When To use: The for...in loop helps you go through each item in an object or an array. It’s like checking each item one by one.

  • *How It Works: *

  1. The loop starts by creating a variable (often called key) to store the current property name.

  2. The loop checks if the current property exists in the object.

  3. If the property exists, the code inside the loop is executed.

  4. The loop moves to the next property.

  • Example:

Image description

For of Loop

  • When To use: When you want to loop through values of an array or other iterable.

  • *How It Works: *

  1. The loop creates a variable to hold the current value.

  2. The loop iterates over each value in the iterable object.

  3. The current value is assigned to the variable.

  • Example:

Image description

Note: If you Know more please share.

Mail: mdabdurrazzakrakib290@gamil.com

Top comments (0)