본문으로 건너뛰기

What are Conditional Statements?

What are Conditional Statements?

Conditional statements control the flow of program execution based on whether a certain condition is true or false.

Just as in daily life we make choices like "If it rains, I will use an umbrella, otherwise I won't," in code, we can execute different actions based on certain conditions.


The Necessity of Conditional Statements

Programs operate through data and conditions applied to that data.

Conditional statements are an essential element when designing programs to behave differently depending on the state of the data.

For example, you can use conditional statements to display different messages based on user input, or in a game, end the game when a character's health reaches zero.


If Statement

  • Basic Structure of an If Statement
if (conditional expression) {
// Code to be executed if the conditional expression is true
}

What is a Conditional Expression?

A conditional expression is an expression that yields a true or false value.

For example, the expression x > 10 is true if the value of x is greater than 10, and false otherwise.


Example

let age = 16;
if (age >= 20) {
console.log('You are an adult.');
} else {
console.log('You are a teenager.');
}
// Output: You are a teenager.

If-Else Statement

  • Basic Structure of an If-Else Statement
if (conditional expression) {
// Code to be executed if the conditional expression is true
} else {
// Code to be executed if the conditional expression is false
}

Handling Multiple Conditions

With an if-else statement, you can choose to execute code between two situations.


Example

let score = 85;
if (score >= 90) {
console.log('Grade A');
} else if (score >= 80) {
console.log('Grade B');
} else {
console.log('Grade C');
}
// Output: Grade B

If-Else Statement

  • Handling Multiple Conditions

When you want to check several conditions in a row, you use an if-else statement.

Only the code block for the first condition that is true will be executed.

Example

let temperature = 15;
if (temperature > 25) {
console.log('It\'s hot!');
} else if (temperature > 15) {
console.log('It\'s nice!');
} else {
console.log('It\'s cold!');
}
// Output: It's nice!