SimpleTuts.com

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:

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:


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

  1. User enters their age.
  2. When the button is clicked, the function checkAge() runs.
  3. JavaScript checks whether the age is greater than or equal to 18.
  4. The result is displayed on the webpage.

8. Practice Exercise

Create a Login Validation System.

Inputs:

Conditions:


9. What Students Learned


Next Chapter

Chapter 4: Loops in JavaScript (for, while, do...while) with Real-Life Example: Multiplication Table Generator