Code highlights logo

Learn

Conditional Statements

What are Conditional Statements?

In programming, conditional statements are powerful tools that allow us to control the flow of our code based on certain conditions. They help us make decisions and execute different blocks of code depending on whether a condition is true or false.

Why are Conditional Statements Important?

Conditional statements are essential in programming as they enable our programs to make intelligent decisions and respond dynamically to different scenarios. They allow us to create more interactive and responsive applications.

Examples of Conditional Statements

Here are a few examples of conditional statements:

  1. if statement: The if statement allows us to run a block of code only if a specified condition is true. For example:
    1if (age >= 18) {
    2 console.log("You are eligible to vote!");
    3}
  2. if...else statement: The if...else statement allows us to specify two blocks of code: one to be executed if the condition is true, and another if the condition is false. For example:
    1if (score >= 70) {
    2 console.log("Congratulations! You passed the exam.");
    3} else {
    4 console.log("Sorry, you did not pass the exam.");
    5}
  3. else if statement: The else if statement allows us to specify multiple conditions to be tested sequentially. The code block associated with the first condition that evaluates to true will be executed. For example:
    1if (time < 10) {
    2 console.log("Good morning!");
    3} else if (time < 20) {
    4 console.log("Good day!");
    5} else {
    6 console.log("Good evening!");
    7}

Sign up to start coding

Already have an account?

Sign In

Course content