๐
๐จ
Conditionals help your code make choices, like choosing which path to take!
Making Decisions
Conditionals let your code make decisions based on conditions. If something is true, do this. Otherwise, do something else!
It's like asking questions: "Is it raining? If yes, take an umbrella. If no, wear sunglasses."
๐ก
๐จ
The if Statement
The simplest conditional checks if something is true:
1const age = 18;23if (age >= 18) {4 console.log("You can vote!");5}67// The code inside { } only runs8// if the condition is true
๐ค
๐จ
if...else
Add else to handle when the condition is false:
1const age = 15;23if (age >= 18) {4 console.log("You can vote!");5} else {6 console.log("Too young to vote.");7}89// Output: "Too young to vote."
๐ก
๐จ
if...else if...else
Chain multiple conditions with else if:
1const score = 85;23if (score >= 90) {4 console.log("Grade: A");5} else if (score >= 80) {6 console.log("Grade: B");7} else if (score >= 70) {8 console.log("Grade: C");9} else {10 console.log("Grade: F");11}1213// Output: "Grade: B"
๐ค
๐จ
Comparison Operators
===equal to!==not equal>greater than<less than>=greater or equal<=less or equal1// Always use === instead of ==25 === 5 // true35 === "5" // false (different types)45 == "5" // true (loose, avoid!)
๐ฎ
Try It Yourself!
Adjust the sliders to see how conditionals evaluate different values!
Age Checker
You are an adult!
1if (18 >= 18) {2 // Adult3} else if (18 >= 13) {4 // Teenager5} else {6 // Child7}
Grade Calculator
Grade: C
๐งช Code Lab - Try It Yourself!
๐งชConditionals Lab
Enter RunShift+Enter New line History
๐Output
Run some code to see the output here!
๐กTry These Examples