Hi everyone! Welcome to my another blog from JavaScript series. Today I am going to write about the important parts of Loops. It's a very interesting topic also. So will se some about that,
Think of a loop like a cycle or a repeating action. For example, if you want to say “Hello” 5 times, you can use a loop instead of writing it 5 times.
Initialization – Start Point:
-> This is where the loop begins.
-> You create a variable (like i) and give it a starting value.
Think of it like starting a car.
You must turn on the key before driving.
Example:
let i = 0;
Here, i is starting at 0.
Condition – When to Continue:
-> This checks if the loop should keep going.
-> If the condition is true, the loop runs again.
-> If it’s false, the loop stops.
Think of it like a traffic signal.
If it's green, you keep going. If red, you stop.
Example:
i < 5;
This means: "Keep going as long as i is less than 5."
Increment or Decrement – How to Move:
-> After each loop, you change the value of the variable.
-> You either increase or decrease it.
Think of it like taking steps.
You must move forward or backward each time.
Example:
i++;
This means: "Add 1 to i every time."
Full Loop Example:
for (let i = 0; i < 5; i++) {
console.log("Hello");
}
What’s Happening?
- Start with i = 0
- Check i < 5 (is 0 less than 5?) Yes
- Print "Hello"
- Add 1 to i → now i = 1
- Repeat steps 2 to 4
- When i = 5, the condition is false → loop stops
Real-Life Example:
Imagine you have 5 mangoes and want to count them one by one.
You will see:
So these are the basic introduction about Loops. Here I showed the For Loops examples. My upcoming blogs will cover all the loop types. Thank you for reading my blog. See you in my next Blog.
Top comments (0)