Lecture on JavaScript Conditional Statements

Jul 21, 2024

Lecture on JavaScript Conditional Statements

Presenter: Davin Rady

Key Concepts

Importance of Conditional Statements

  • Decisions in programming are based on data and conditions (true/false values).
  • Comparison of values results in boolean values (true or false).
  • Conditional statements guide the flow of execution based on these boolean values.

Introduction to if-else Statements

  • if-else: Fundamental structure for making decisions in JavaScript.

Example: Comparing Two Values

  • Task: Compare two numbers and print the greater one.
  • Steps to Implement:
    1. Declare two variables: num1 and num2.
    2. Use comparison num1 > num2 to get a boolean result.
    3. Use an if statement to print if num1 is greater.
    4. Optionally, use an else statement to handle the case where num2 is greater.
    5. Example Code snippet:
let num1 = 6;
let num2 = 4;
if (num1 > num2) {
    console.log("num1 is greater");
} else {
    console.log("num2 is greater");
}
console.log("Bye");

Adding Complexity: Multiple Statements and Nested Conditions

  • Multiple statements can be included within if or else using {} curly brackets.
  • Example:
if (num1 > num2) {
    console.log("num1 is greater");
    console.log("Yay");
} else {
    console.log("num2 is greater");
}

Logical Operators in Conditions

  • Use logical operators (&&, ||) to combine multiple conditions.
  • Example: Find the greatest of three numbers (num1, num2, num3).
let num1 = 8;
let num2 = 6;
let num3 = 7;
if (num1 > num2 && num1 > num3) {
    console.log("num1 is greatest");
} else if (num2 > num1 && num2 > num3) {
    console.log("num2 is greatest");
} else {
    console.log("num3 is greatest");
}

Refining Conditions

  • Optimization Tip: Reduce redundant comparisons once some conditions are known.

Practical Assignment

  • Task: Use if-else to determine if a given number is even or odd.

Conclusion

  • if, else, else if are crucial for control flow in JavaScript.
  • Practice with simple examples to understand the syntax and logic.

End of Lecture