Conditional statements are like making decisions in your code. They let your program choose different paths based on whether something is true or false. This makes your programs smart and able to react to different situations.
Conditional Statements
Conditional Statements
Imagine you are playing a game. If your score is high enough, you win. If not, you lose. This "if...then" logic is exactly what conditional statements do in programming.
They allow your JavaScript code to check conditions. Based on whether a condition is true or false, your code will run different parts. This is how programs make choices and respond to user input or data.
What are Conditionals?
Conditional statements are control structures that execute different blocks of code based on whether a specified condition evaluates to true or false.
if
Runs code only if a specific condition is true.
else if
Checks another condition if the first 'if' condition was false.
else
Runs code if all previous 'if' and 'else if' conditions were false.
switch
A different way to handle many choices based on a single value.
Your First 'if' Statement
Your First 'if' Statement
The simplest conditional statement is if. You write if, then a condition inside parentheses (), and then the code to run inside curly braces {}.
The condition inside the parentheses must result in either true or false. If it's true, the code inside the curly braces runs. If it's false, that code is skipped.
1// Create a variable for the user's age2let userAge = 12;34// Check if the user's age is greater than or equal to 135// The condition `userAge >= 13` will be true or false6if (userAge >= 13) {7 // This code runs ONLY if userAge is 13 or more8 console.log("You are old enough to create an account.");9}1011console.log("Program continues here.");1213// Let's try with a different age14let anotherAge = 18;15if (anotherAge >= 13) {16 console.log("This message will show because 18 is >= 13.");17}
Do not use a single equals sign for comparison
A single equals sign = is for assigning a value to a variable (let x = 10;). A double == or triple === equals sign is for comparing values.
If you accidentally write if (userAge = 13), it will assign 13 to userAge and then treat 13 as true (because it's a non-zero number). This is a common mistake that causes unexpected behavior.
Always use == or === for comparisons in if statements.
Adding 'else' and 'else if'
Adding 'else' and 'else if'
Often, you want to do something if a condition is true, and something else if it's false. That's where the else statement comes in. It provides an alternative path for your code.
If you have many conditions to check, you can use else if. This lets your code check one condition, then another, and then another, until one is true. If none are true, the final else block will run.
1// Variable for a game score2let score = 75;34// Check the score to give a rank5if (score >= 90) {6 // This runs if score is 90 or more7 console.log("Rank: Gold Star!");8} else if (score >= 70) {9 // This runs if score is NOT >= 90, BUT IS >= 7010 console.log("Rank: Silver Medal.");11} else if (score >= 50) {12 // This runs if score is NOT >= 70, BUT IS >= 5013 console.log("Rank: Bronze Tier.");14} else {15 // This runs if NONE of the above conditions were true16 console.log("Rank: Try Again.");17}1819// Let's test with a different score20let finalScore = 40;21if (finalScore >= 90) {22 console.log("Gold Star!");23} else if (finalScore >= 70) {24 console.log("Silver Medal.");25} else if (finalScore >= 50) {26 console.log("Bronze Tier.");27} else {28 console.log("Try Again."); // This will print for finalScore = 4029}
let age = 10;if (age >= 18) {console.log("Adult");} else {if (age >= 13) {console.log("Teen");} else {console.log("Child");}}
let age = 10;if (age >= 18) {console.log("Adult");} else if (age >= 13) {console.log("Teen");} else {console.log("Child");}
if/else if vs. switch
if/else if vs. switch
When you have many possible outcomes based on a single value, an if/else if chain can become very long. The switch statement offers a cleaner way to handle these situations.
The switch statement evaluates a single expression. Then it compares the result to several case values. If a match is found, the code for that case runs. If no case matches, the default code runs.
// Using if/else if for a day of the weeklet day = 'Monday';if (day === 'Monday') {console.log('Start of the week.');} else if (day === 'Friday') {console.log('Almost weekend!');} else if (day === 'Saturday' || day === 'Sunday') {console.log('It\'s the weekend!');} else {console.log('Midweek.');}
// Using switch for a day of the weeklet day = 'Monday';switch (day) {case 'Monday':console.log('Start of the week.');break;case 'Friday':console.log('Almost weekend!');break;case 'Saturday':case 'Sunday':console.log('It\'s the weekend!');break;default:console.log('Midweek.');}
// Using if/else if for a day of the weeklet day = 'Monday';if (day === 'Monday') {console.log('Start of the week.');} else if (day === 'Friday') {console.log('Almost weekend!');} else if (day === 'Saturday' || day === 'Sunday') {console.log('It\'s the weekend!');} else {console.log('Midweek.');}
// Using switch for a day of the weeklet day = 'Monday';switch (day) {case 'Monday':console.log('Start of the week.');break;case 'Friday':console.log('Almost weekend!');break;case 'Saturday':case 'Sunday':console.log('It\'s the weekend!');break;default:console.log('Midweek.');}
When to use switch
Use switch when you are checking a single variable against many possible exact values. For example, if you have a status variable that can be 'pending', 'approved', or 'rejected'.
Use if/else if when you are checking ranges of values (like score >= 90) or complex conditions involving multiple variables (age > 18 && hasLicense).
Building a Simple Price Calculator
Building a Simple Price Calculator
Let's use conditional statements to build a small program that calculates a price with different discounts. This shows how decisions in your code can change the final outcome.
We will apply a discount based on the total purchase amount. More money spent means a bigger discount.
Set the initial price
Start with a base price for the items.
1let basePrice = 250;2let discount = 0;3let finalPrice = 0;
Apply a discount based on price
Use if, else if, else to decide the discount percentage.
1if (basePrice >= 500) {2 discount = 0.20; // 20% off3} else if (basePrice >= 200) {4 discount = 0.10; // 10% off5} else {6 discount = 0; // No discount7}
Calculate the final price
Apply the chosen discount to the basePrice to get the finalPrice.
1finalPrice = basePrice * (1 - discount);2console.log(`Base Price: $${basePrice}`);3console.log(`Discount Applied: ${discount * 100}%`);4console.log(`Final Price: $${finalPrice}`);
Test with different prices
Change basePrice to see how the discount changes.
1/* Try changing basePrice to:2- 100 (no discount)3- 300 (10% discount)4- 600 (20% discount)5*/
Remember 'break' in switch statements
If you forget break; at the end of a case block in a switch statement, JavaScript will continue executing the code in the next case block, even if it doesn't match the value. This is called fall-through and often leads to bugs. Always include break; unless you specifically intend fall-through.
Comparison and Logical Operators
Comparison and Logical Operators
The conditions inside your if statements use comparison operators to check relationships between values. They always return true or false.
Logical operators let you combine multiple conditions. You can check if two things are true at the same time, or if at least one of several things is true.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to (loose) | 5 == '5' | true |
| === | Strictly equal to | 5 === '5' | false |
| != | Not equal to (loose) | 5 != '6' | true |
| !== | Strictly not equal to | 5 !== '5' | true |
| > | Greater than | 10 > 5 | true |
| < | Less than | 10 < 5 | false |
| >= | Greater than or equal to | 10 >= 10 | true |
| <= | Less than or equal to | 10 <= 9 | false |
| && | AND (both true) | true && false | false |
| || | OR (at least one true) | true || false | true |
| ! | NOT (reverses true/false) | !true | false |
Test Your Knowledge
Test Your Knowledge
Which statement will execute if score is 85?
What is the primary purpose of the break keyword in a switch statement?
What will console.log(10 == '10'); print?
Which of these JavaScript values is considered 'falsy' in a conditional statement?
Quick Reference
Quick Reference
- 1if statement — runs code if a condition is
true. Example:if (age > 18) { ... } - 2else if — checks another condition if the previous
iforelse ifwasfalse. - 3else — runs code if all preceding
ifandelse ifconditions werefalse. - 4Conditions — always evaluate to
trueorfalseusing comparison operators. - 5Strict Equality (===) — always prefer
===over==to avoid unexpected type conversions. - 6Logical AND (&&) —
condition1 && condition2istrueonly if BOTH conditions aretrue. - 7Logical OR (||) —
condition1 || condition2istrueif at least ONE condition istrue. - 8switch statement — useful for checking a single variable against many possible exact values.
- 9break keyword — essential in
switchcaseblocks to prevent 'fall-through' to the next case. - 10Ternary Operator — a shortcut for simple
if/elseassignments:condition ? valueIfTrue : valueIfFalse.
Loops
Learn how to repeat actions in your code using for and while loops.
Functions
Organize your code into reusable blocks to perform specific tasks.
Data Types
Understand different types of values like numbers, strings, and booleans.
Comparison Operators
Dive deeper into how JavaScript compares different values and types.
You've Mastered Conditional Logic!
You now understand how to make your JavaScript programs smart by using if, else if, else, and switch statements. You can use comparison and logical operators to create powerful conditions, allowing your code to react dynamically to different situations and inputs.
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.