Conditional Statements - Exercise 1

Conditional statements let a program choose which code to run based on a boolean condition. They make it possible to handle different inputs, states, and user actions instead of always following one path.

Common choices are if, else if, and else for ranges or complex conditions, and switch for matching one expression against several values. The ternary operator is useful for a short two-way choice.

An if statement evaluates a condition and runs its block only when the result is truthy. Use strict comparisons when checking values so type conversions do not produce surprising matches.

javascript

const score = 75;
if (score >= 60) {
  console.log("Pass");
}

The syntax of the if statement in JavaScript is as follows:

javascript

if (condition) {
    // code to be executed if condition is true
}

The else block provides the fallback path when the preceding if condition is falsy. Only one branch of an if/else pair runs, which makes the two possible outcomes explicit.

You can use the else statement in JavaScript to execute a block of code if the condition specified in the if statement is false.

javascript

if (condition) {
    // code to be executed if condition is true
} else {
    // code to be executed if condition is false
}

The else if branch tests another condition only when the earlier conditions were false. JavaScript stops at the first matching branch, so order the conditions from most specific to most general.

You can use the else if statement in JavaScript to specify additional conditions to be tested if the previous condition(s) are false.

javascript

if (condition1) {
    // code to be executed if condition1 is true
} else if (condition2) {
    // code to be executed if condition2 is true
} else {
    // code to be executed if all conditions are false
}

A switch compares one expression with several case values and runs the first matching block. Use break when you want to prevent execution from falling through to the next case.

You can use the switch statement in JavaScript to evaluate an expression and execute a corresponding case block based on the value of the expression.

javascript

switch (expression) {
    case value1:
        // code to be executed if expression matches value1
        break;
    case value2:
        // code to be executed if expression matches value2
        break;
    default:
        // code to be executed if expression doesn't match any case
}