Lecture

Combining Conditionals, Loops, and Functions

Conditionals, loops, and functions are the fundamental building blocks for controlling logic in programming.

Let's briefly review the role of each.


Conditionals

Conditionals allow you to execute code selectively based on given conditions.

Displaying Different Messages Based on Temperature
function checkTemperature(temperature) { if (temperature > 68) { console.log('It\'s warm weather'); } else if (temperature > 50) { console.log('It\'s cool weather'); } else { console.log('It\'s cold weather'); } } checkTemperature(59);

Loops

Loops execute code repeatedly based on given conditions.

Printing Only Even Numbers from 1 to 10
for (let i = 1; i <= 10; i++) { if (i % 2 === 0) { console.log(i); } }

Functions

Functions package code into reusable units.

Calculating the Average of an Array of Numbers
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 using these three logical structures together, you can perform more complex tasks.

The code in the center of the screen first calculates the average score using the getAverage function, then uses a combination of loops and conditionals to print only the scores higher than the average.

In this way, by appropriately combining conditionals, loops, and functions, you can solve a variety of complex tasks with ease.

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run

Execution Result