Welcome to the exciting world of making decisions in your code! Just like in real life, computers need to be able to make choices based on certain conditions. This is where conditional statements come into play, and we'll start with the most fundamental one: the 'if' statement.
The 'if' statement is your tool for executing a block of code only if a specific condition is true. Think of it as asking a question: 'If this is true, then do that.' If the answer to the question is 'yes' (true), the code inside the 'if' statement runs. If the answer is 'no' (false), the code is skipped.
The basic structure of an 'if' statement looks like this:
if (condition) { // code to execute if the condition is true }
The condition is an expression that evaluates to either true or false. This could be a comparison (like checking if one number is greater than another), a check for equality, or a more complex combination of these.
let temperature = 25;
if (temperature > 20) {
console.log('It's a warm day!');
}In the example above, the condition is temperature > 20. Since 25 is indeed greater than 20, the condition evaluates to true, and the message 'It's a warm day!' is printed to the console.
let isRaining = false;
if (isRaining) {
console.log('Don't forget your umbrella!');
}Here, isRaining is false. Because the condition is false, the code inside the if statement (the console.log command) is not executed. The program simply moves on to whatever comes next.
graph TD;
A[Start]
B{Is condition true?}
C[Execute code block]
D[End]
A --> B
B -- Yes --> C
B -- No --> D
C --> D
This flowchart visually represents how an 'if' statement works. The program reaches a decision point (the condition). If the condition is met (true), it proceeds to execute a specific set of instructions. If not (false), it skips those instructions and continues.