๐Ÿ”€

Conditionals

๐ŸŽ‰
๐Ÿ’จ
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;
2
3if (age >= 18) {
4 console.log("You can vote!");
5}
6
7// The code inside { } only runs
8// if the condition is true
๐Ÿค”
๐Ÿ’จ

if...else

Add else to handle when the condition is false:

1const age = 15;
2
3if (age >= 18) {
4 console.log("You can vote!");
5} else {
6 console.log("Too young to vote.");
7}
8
9// Output: "Too young to vote."
๐Ÿ’ก
๐Ÿ’จ

if...else if...else

Chain multiple conditions with else if:

1const score = 85;
2
3if (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}
12
13// Output: "Grade: B"
๐Ÿค”
๐Ÿ’จ

Comparison Operators

===equal to
!==not equal
>greater than
<less than
>=greater or equal
<=less or equal
1// Always use === instead of ==
25 === 5 // true
35 === "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 // Adult
3} else if (18 >= 13) {
4 // Teenager
5} else {
6 // Child
7}

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