Navani 6B

Introduction to Conditional Statements

  • Definition: Conditional statements make decisions based on conditions in programming. They determine if a condition is true or false and execute corresponding code.

Example of a Simple Conditional Statement

  • Code Example:

if (5 > 3) {  
    document.write("5 is greater than 3");  
}  

Else-If Construction

  • Purpose: Used in JavaScript to evaluate multiple conditions, such as checking if a number is positive, negative, or zero.

  • Functionality: If the first condition is false, the program checks the next else if condition.

Syntax for Conditional Statements

  • General Syntax:

if (condition1)  
{  // Code runs if condition1 is true  
}  
else if (condition2)  
{  // Code runs if condition1 is false but condition2 is true  
}  
else  
{  // Code runs if all conditions above are false  
}  

Difference Between parseInt and Number

  • parseInt: Converts input to a whole number (removes decimals).

  • Number: Converts input to a number (keeps decimals if present).

Nested If Statements

  • Definition: An if statement within another if statement. Checks the inner condition only if the outer condition is true.

  • Use Case: Useful when a decision depends on another condition.

Nested If Example

  • First Condition: Checks if the username is "admin".

    • Inner Condition:

      • Checks if the password is "1234".

        • Result: Shows "Login Successful".

      • Else: If the password is incorrect, shows "Wrong Password".

  • Else for Username: If the username isn’t "admin", displays "Invalid Username".