Logo
Unit 4 – Control Structures: Conditional Statements

Control Structures: Conditional Statements

Duration: 5 minutes

Hello, future JavaScript programmers!

You now have a solid understanding of operators and data types, and we’re moving on to control structures, one of the most important features of any programming language. In this module, we’ll talk specifically about conditional statements.

These provide your code the ability to decide in accordance with specific circumstances, resulting in dynamic and interactive applications

Understanding Conditional Statements in JavaScript

Conditional statements are used to execute different code blocks based on different conditions. In JavaScript, we primarily use the if, else if, and else statements for this purpose:

  • if Statement: It tests a condition. If the condition is true, it executes a block of code.
if (condition) {
  // code to be executed if the condition is true
}

  • else if Statement: It tests another condition if the previous if the condition is false.
if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition2 is true
}

  • else Statement: If none of the conditions are true, the code inside the else block gets executed.
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 none of the conditions are true
}

Creating a Program Using Conditional Statements

Let’s illustrate this with a simple example. Imagine you want to grade students based on their marks:

let marks = 85;
if (marks >= 90) {
  console.log("Grade: A");
} else if (marks >= 80) {
  console.log("Grade: B");
} else if (marks >= 70) {
  console.log("Grade: C");
} else if (marks >= 60) {
  console.log("Grade: D");
} else {
  console.log("Grade: F");
} // This will output: 'Grade: B'

Here, the program checks each condition sequentially. Since the marks is 85, it satisfies the condition of being greater than or equal to 80 but less than 90, and thus, the program outputs ‘Grade: B’.

Exercise

Your current task is to develop a system that ascertains a person’s eligibility to vote. They may vote if they are 18 years of age or older.

They cannot if not. Additionally, congratulate them on being a new voter if they are exactly 18 years old. You can practice and improve your grasp of conditional statements with the help of this activity.

Conclusion

Well done for delving into JavaScript’s conditional statements! The power to incorporate dynamic and decision-making functionalities into your programs is unlocked by mastering them. With these fundamentals in place, you’re making steady progress toward mastering JavaScript programming.

Stay curious and keep coding!

Next Tutorial: Control Structures: Loops

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!