Loops and Conditionals in JavaScript
Loops and conditionals are essential building blocks in programming. They allow you to control the flow of your code based on certain conditions and iterate over a block of code multiple times. In JavaScript, we have if-else
statements for decision-making and for
and while
loops for repeating actions.
1. if-else Statements
The if-else
statement allows you to execute code based on whether a condition is true
or false
.
Syntax:
if (condition) {
// Code to run if the condition is true
} else {
// Code to run if the condition is false
}
Example:
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
In this example, the if
checks if age
is greater than or equal to 18. If true, the message “You are an adult” is logged; otherwise, “You are a minor” is logged.
2. for Loop
The for
loop is used when you know how many times you need to repeat a block of code. It runs for a specific number of iterations, defined by the loop’s condition.
Syntax:
for (let i = 0; i < limit; i++) {
// Code to be executed each time
}
let i = 0
initializes the loop counter.i < limit
is the condition that keeps the loop running.i++
increases the counter by one after each iteration.
Example:
for (let i = 1; i <= 5; i++) {
console.log("Iteration: " + i);
}
This loop will run 5 times, logging the iteration number to the console.
3. while Loop
The while
loop runs as long as a condition is true
. It’s useful when you don’t know in advance how many iterations are needed, and you want to repeat until a certain condition is met.
Syntax:
while (condition) {
// Code to be executed as long as the condition is true
}
Example:
let counter = 1;
while (counter <= 5) {
console.log("Iteration: " + counter);
counter++; // Increment counter
}
This loop will behave similarly to the for
loop example above, logging “Iteration: 1” to “Iteration: 5”.
4. Practical Example: Number Guessing Game
Now, let’s combine conditionals and loops to create a simple number guessing game. In this game, the player needs to guess a randomly generated number between 1 and 10.
Example:
let randomNumber = Math.floor(Math.random() * 10) + 1; // Random number between 1 and 10
let userGuess;
let attempts = 0;
while (userGuess !== randomNumber) {
userGuess = prompt("Guess a number between 1 and 10:");
if (userGuess == randomNumber) {
alert("Congratulations! You guessed the correct number.");
} else if (userGuess < randomNumber) {
alert("Too low! Try again.");
} else if (userGuess > randomNumber) {
alert("Too high! Try again.");
}
attempts++;
}
console.log("You guessed the number in " + attempts + " attempts.");
In this example:
- A random number between 1 and 10 is generated using
Math.random()
. - The
while
loop keeps running until the player guesses the correct number. - Inside the loop, the
if-else
statements check if the guess is too high, too low, or correct and provide feedback. - After the correct guess, a message displays how many attempts it took to guess the number.
5. Combining Loops and Conditionals
Conditionals and loops can be combined in many ways to create complex behaviors. For instance, you can use a for
loop to iterate over an array and use if-else
to filter out certain values.
Example: Filtering Even Numbers
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
console.log(numbers[i] + " is an even number.");
}
}
This example uses a for
loop to iterate through the numbers
array and an if
statement to check whether each number is even.
Conclusion
- Conditionals like
if-else
help make decisions in code based on conditions. - Loops like
for
andwhile
help repeat code for a specified number of times or while a condition remains true. - Combining loops and conditionals can help build interactive features like games, filters, and more.
Mastering these fundamental programming concepts will enhance your ability to write more efficient and interactive JavaScript code.