Hey there, friend!
Welcome to our Boolean Logic tutorial! Today, we're going to explore the world of conditional statements, and I'm excited to guide you through it.
Task: Check if a user is over 18 years old and has confirmed their email.
Let's get started!
Open your index.js
file and get ready to code!
Step 1: Define the variables
We need to define two variables: age
and emailConfirmed
. Set their values to 20
and true
, respectively, for our example.
let age = 20let emailConfirmed = true
Run the code by clicking the "Run" button to ensure everything is working as expected. You shouldn't see any output yet, as we haven't added any output statements.
Step 2: Understand Boolean Logic
Boolean Logic is a way to make decisions based on true or false values. We'll use the &&
(AND) operator to check if both conditions are true.
Think of it like a bouncer at a club. The bouncer checks if you're over 18 (condition 1) AND if you have a valid ID (condition 2). If both conditions are true, you get in!
Step 3: Write the conditional statement
Let's write an if
statement to check if the user is over 18 and has confirmed their email.
if (age >= 18 && emailConfirmed) { // code to execute if conditions are true}
Step 4: Add an output statement
Let's add a console log statement to display a message if the conditions are true.
if (age >= 18 && emailConfirmed) { console.log("You're eligible to access the system!")}
Run the code again! You should see the output "You're eligible to access the system!" in the console.
What's happening?
The if
statement checks if age
is greater than or equal to 18 (age >= 18
) and if emailConfirmed
is true
. Since both conditions are true, the code inside the if
block executes, and we see the output message.
Try it yourself!
Change the values of age
and emailConfirmed
to see how the output changes. For example, set age
to 17 or emailConfirmed
to false
and run the code again.
Conclusion
You've just learned how to use Boolean Logic with if
statements to make decisions in your code! This is a fundamental concept in programming, and you'll use it extensively in your projects.
Keep practicing, and soon you'll be a master of conditional statements!
What's next? We'll explore more advanced conditional statements and loops in our future tutorials. Stay tuned!
Tests