JavaScript Conditionals
Conditional Statements
When you write code, you often want to perform different
actions for different conditions.
Conditional statements run different code depending on
a true or false condition.
Conditional statements include:
if
if...else
if...else if...else
switch
ternary (? :)
When to use Conditionals
Use if to specify a code block to be executed, if a specified condition
is true
Use else to specify a code block to be executed, if the same
condition is false
Use else if to specify a new condition to test, if the first condition
is false
Use switch to specify many alternative code blocks to be executed
Use (? :) (ternary) as a shorthand for if...else
The if Statement
Use if to specify a code block to be executed, if a specified condition
is true.
Syntax
if (condition) {
// code to execute if the condition is true
}
The else Statement
Use else to specify a code block to be executed, if the same condition
is false.
Syntax
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
The else if Statement
Use else if to specify a new condition to test, if the first condition is false.
Syntax
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if the condition1 is false and condition2 is
true
} else {
// code to execute if the condition1 is false and condition2 is
false
}
The switch Statement
Use switch to specify many alternative code blocks to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Ternary Operator (? :)
Use (? :) (ternary) as a shorthand for if...else.
Example
condition ? expression1 : expression2
JavaScript if
Example 1
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript if</h1>
<p>Display "Good day!" if the hour is less than 18:00:</p>
<p id="demo">Good Evening!</p>
<script>
if (new Date().getHours() < 18) {
[Link]("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
Example 2
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript if</h1>
<p id="demo"></p>
<script>
let age = 18;
let text = "You can Not drive!";
if (age >= 18) {
text = "You can drive!";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript Nested if
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Nested if</h1>
<p id="demo"></p>
<script>
let age = 16;
let country = "USA";
let text = "You can Not drive!";
if (country == "USA") {
if (age >= 16) {
text = "You can drive!";
}
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript else
The else Statement
Use the else statement to specify a block of code to be executed if
a condition is false.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript if .. else</h1>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
[Link]("demo").innerHTML = greeting;
</script>
</body>
</html>
The else if Statement
Use the else if statement to specify a new condition if the first is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
[Link]("demo").innerHTML = greeting;
</script>
</body>
</html>
The Conditional (Ternary)
Operator
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Ternary Operator</h1>
<p id="demo"></p>
<script>
// Using the ternary operator
let price = 10;
let isMember = true;
let discount = isMember ? 0.2 : 0;
let total = 10 - (price * discount)
[Link]("demo").innerHTML = "The price is " + total;
</script>
</body>
</html>
Description
The conditional operator is a shorthand for writing
conditional if...else statements.
It is called a ternary operator because it takes three operands.
Syntax
(condition) ? expression1 : expression2
Parameters
Parameter Description
condition Required.
The condition to be tested.
An expression that evaluates to true or false.
? Required.
The operator separating the condition from the expressions.
expression1 Required.
The value to return if the condition is true.
: Required.
The operator separating the expressions.
expression2 Required.
The value to return if the condition is false.
Note
The conditional (ternary) operator is the only JavaScript operator that takes
three operands.
Browser Support
() ? x : y is an ES1 feature (JavaScript 1997).
It is fully supported in all browsers:
Chrome IE Edge Firefox Safari Opera
Yes Yes Yes Yes Yes Yes
JavaScript Switch Statement
Switch Control Flow
Based on a condition, switch selects one or more code blocks to be
executed.
switch executes the code blocks that matches an expression.
switch is often used as a more readable alternative to many if...else
if...else statements, especially when dealing with multiple possible
values.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
If there is no match, no code is executed.
Example
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Control Flow</h1>
<h2>The switch Statement</h2>
<p id="demo"></p>
<script>
let day;
let date = new Date().getDay();
switch (date) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
[Link]("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>
The break Keyword
When JavaScript reaches a break keyword, it breaks out of the
switch block.
This will stop the execution inside the switch block.
No more statements in the switch block will be executed.
It is not necessary to break the last case. The switch ends (breaks) there
anyway.
Note
The break keyword is crucial for preventing a "fall-through."
Without break, the code will continue to execute the next case blocks (and
the default block if present) even if their values do not match the
expression.
The default Keyword
The default keyword specifies a block of code to run if there is no case
match.
The default keyword is optional.
The default can act as a fallback:
Example
The getDay() method returns the weekday as a number between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript switch Controls</h1>
<h2>The default Keyword</h2>
<p id="demo"></p>
<script>
let text;
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript Booleans
The Boolean Data Type
In JavaScript, a Boolean is a primitive data type that can only have one of
two values:
true or false
The Boolean value of an expression is the basis for all
JavaScript comparisons and conditions.
Key Boolean Characteristics
true and false are boolean data types
true and false are the only possible boolean values
true and false must be written in lowercase
true and false must be written without quotes
Boolean Use Cases
Very often, in programming, you will need a data type that can represent
one of two values, like:
yes or no
on or off
true or false
Boolean values are fundamental for logical operations and control flow in
JavaScript programming.
Comparisons
All JavaScript comparison operators (like ==, !=, <, >)
return true or false from the comparison.
Given that x = 5, the table below explains comparison:
Description Example Returns
Not equal to (x == 8) false
Unequal to (x != 8) true
Greater than (x > 8) false
Less than (x < 8) true
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Boolean</h1>
<h2>Use Case: Equality</h2>
<p id="demo"></p>
<script>
let x = 5;
[Link]("demo").innerHTML = (x == 8);
</script>
</body>
</html>
Conditions
Booleans are extensively used in if statements to determine the code
blocks to execute based on the logic.
Example Result
if (day == "Monday") true or false
if (salary > 9000) true or false
if (age < 18) true or false
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Boolean</h1>
<h2>Use Case: if .. else</h2>
<p id="demo"></p>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 18) {
greeting = "Good day!";
} else {
greeting = "Good evening!";
}
[Link]("demo").innerHTML = greeting;
</script>
</body>
</html>
Class tasks
1. User Role Check
Input a user role ("admin", "editor", "viewer").
Display different messages for each role.
2. Time-Based Greeting
Input current hour (0–23).
Display "Good morning", "Good afternoon", or "Good evening".
3. switch Statement – Day of the Week
Use switch to print the day name when a number (1–7) is entered.
4. Login Simulation
Check if username and password match predefined values.
If both are correct → "Login successful", else "Invalid credentials".
5. Discount Eligibility
If purchase amount > 5000 → 10% discount, if between 2000–5000 → 5%, otherwise → no
discount.
6. Weather Message Generator
Combine logical and comparison operators to give a message:
Rainy + cold → “Carry an umbrella and wear a jacket.”
Rainy + warm → “Carry an umbrella only.”
Else → “Enjoy your day!
7. Electricity Bill Calculator
Based on units consumed:
0–100 → 10 per unit
101–200 → 15 per unit
201+ → 20 per unit
Display total bill.