Conditional Statements in JavaScript
Understanding Conditional Statements in JavaScript
1. What are Conditional Statements?
Conditional statements allow a program to make decisions. The code can perform different actions depending on different conditions.
Example:
- If a student scores more than 50 → Pass
- Otherwise → Fail
JavaScript uses if, else, else if, and switch to handle conditions.
2. The if Statement
The if statement runs code only if the condition is true.
let age = 18;
if(age >= 18){
console.log("You are eligible to vote");
}
Explanation:
- The condition checks if age is greater than or equal to 18.
- If true, the message will be printed.
3. if...else Statement
Used when there are two possible outcomes.
let marks = 40;
if(marks >= 50){
console.log("You Passed");
}else{
console.log("You Failed");
}
4. else if Statement
Used when there are multiple conditions.
let marks = 85;
if(marks >= 90){
console.log("Grade A+");
}
else if(marks >= 75){
console.log("Grade A");
}
else if(marks >= 60){
console.log("Grade B");
}
else{
console.log("Grade C");
}
5. switch Statement
Used when there are many possible fixed values.
let day = 3;
switch(day){
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}
6. Real-Life Example: Age Eligibility Checker
This application checks whether a person is eligible to vote.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Age Eligibility Checker</title>
</head>
<body>
<h2>Voting Eligibility Checker</h2>
<input type="number" id="age" placeholder="Enter your age">
<button onclick="checkAge()">Check</button>
<h3 id="result"></h3>
<script src="app.js"></script>
</body>
</html>
Run Code
app.js
function checkAge(){
let age = Number(document.getElementById("age").value);
let result = document.getElementById("result");
if(age >= 18){
result.innerText = "You are eligible to vote";
}
else{
result.innerText = "You are not eligible to vote";
}
}
Run Code
7. How This Example Works
- User enters their age.
- When the button is clicked, the function
checkAge()runs. - JavaScript checks whether the age is greater than or equal to 18.
- The result is displayed on the webpage.
8. Practice Exercise
Create a Login Validation System.
Inputs:
- Username
- Password
Conditions:
- If username = "admin" and password = "1234" → Login Successful
- Otherwise → Invalid Login
9. What Students Learned
ifstatementsif...elseelse ifswitchstatement- How to build decision-based applications
Next Chapter
Chapter 4: Loops in JavaScript (for, while, do...while) with Real-Life Example: Multiplication Table Generator