DEV Community

Chandru
Chandru

Posted on

JavaScript Conditions and Loops: A Simple Explanation

When I started learning JavaScript, conditions and loops were two topics I came across pretty early.

They may look confusing at first, but the idea is actually simple.

Conditions are used when we want JavaScript to make a decision. For example, if a user is logged in, we can show their profile. If not, we can ask them to log in.

if (isLoggedIn) {
console.log("Welcome!");
}

We can also use else when there are two possible situations.

Loops are used when we want to repeat something without writing the same code again and again.

For example, if we want to print numbers from 1 to 5:

for (let i = 1; i <= 5; i++) {
console.log(i);
}

There are different types of loops in JavaScript, like for and while. Which one we use depends on what we are trying to do.

The main thing I learned is that conditions help us make decisions, while loops help us repeat tasks.

Once you understand these two concepts, writing JavaScript becomes a lot easier because you'll use them in many real projects.

Top comments (0)