Reading Time 2
Number of Words 281
Conditional statements in JavaScript allow you to control the flow of your program based on specific conditions. They help you decide which block of code should be executed depending on whether a condition is true or false.
The if, else if, and else Statements
The if statement checks whether a certain condition is true. If it is, the block of code inside the if statement is executed.
You can also use else if to test multiple conditions, and else to define what happens when none of the previous conditions are met.
Example:
Imagine you want to buy a hotel night that costs €30, and you currently have €50.
const myMoney = 50; if (myMoney > 30) { console.log('Hotel night purchased'); } else if (myMoney == 30) { console.log('Hotel night purchased'); } else { console.log('It has not been possible to buy the hotel night'); }
Explanation:
-
If you have more than €30, the message “Hotel night purchased” will appear.
-
If you have exactly €30, the result is the same.
-
Otherwise, the program will display: “It has not been possible to buy the hotel night”.
Using the Ternary Operator
JavaScript also provides a shorter way to write conditional statements — the Ternary Operator (? :).
It allows you to check a condition and return one of two values depending on whether the condition is true or false.
Example:
const myMoney = 50; myMoney > 30 ? console.log('Hotel night purchased') : console.log('It has not been possible to buy the hotel night');
This code performs the same logic as the previous example, but in a more compact form.
Summary
-
Use
if,else if, andelseto control multiple decision paths in your code. -
Use the ternary operator for shorter, inline conditional checks.
-
These conditionals are essential for controlling logic flow and building interactive programs in JavaScript.