Conditional Logic - If / Else
What Is a Control Structure?
A control structure is a way to tell your program to do something only if a certain condition is met. Think of it like a switch: the wire (your variable) is connected to a light only if a specific condition is true. If the condition isn’t met, the light stays off.
The if Statement
The simplest control structure in JavaScript is the if statement. It checks a condition, and if that condition is true, the code inside the if block runs.
For example:
1if (number === 10) {
2 console.log("Number is 10");
3}Notice we use the strict equality operator (===). As you remember from the previous module, this operator checks that the value is exactly equal to 10 (its data type and value both match).
The if-else Statement
Sometimes, you want your program to do one thing when a condition is true, and something else when it isn’t. That’s where the if-else statement comes in. It works like this:
1if (condition) {
2 // Code if the condition is true
3} else {
4 // Code if the condition is false
5}For instance, you might check if someone is old enough to vote:
1let age = 16;
2if (age >= 18) {
3 console.log("You are an adult.");
4} else {
5 console.log("You are a minor.");
6}Exercises
Learn to hack — start here
Hundreds of interactive courses, virtual labs and CTF challenges in your browser. Start a free trial — no card required.