Combining Conditionals, Loops, and Functions
Conditionals, loops, and functions are the fundamental building blocks for controlling the flow of logic in programming.
Let's briefly review the role of each component.
Conditionals
Conditionals execute code selectively based on a given condition.
function checkTemperature(temperature) {
if (temperature > 20) {
console.log('It is warm');
} else if (temperature > 10) {
console.log('It is cool');
} else {
console.log('It is cold');
}
}
checkTemperature(15);
Loops
Loops repeatedly execute code as long as a given condition is true.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
Functions
Functions group code into reusable units.
function getAverage(numbers) {
let sum = 0;
for (let num of numbers) {
sum += num;
}
return sum / numbers.length;
}
const scores = [90, 85, 78, 92];
const average = getAverage(scores);
console.log(`Average score: ${average}`);
Combining Conditionals, Loops, and Functions
By combining these three logical structures, you can perform more complex tasks.
In the code central to this discussion, the getAverage
function is used to first calculate the average score. Then a loop combined with conditionals is employed to print only the scores that are higher than the average.
By appropriately combining conditionals, loops, and functions, you can efficiently solve a wide variety of complex tasks.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.