We often want to execute different instructions depending on some condition. For example, we have a simple program that removes a file, first asking a user if they are sure. If the answer is “yes” it removes the file; otherwise, it just finishes. To implement this program we should use programming conditions.
A condition in programming consists of 2 parts: the condition and a set of instructions. If the condition is true, the program executes all the instructions from the set.
Let's look at the code of the program that we described before.
if (userAnswer == 'yes') {
deleteFile();
}
We see “userAnswer” variable, which is paired with the ‘yes’ string. If it equals to ‘yes’ our program will delete the file.
Let’s see what types of conditions we can use:
5 == 5(true)
or
5 == 4(false)
or
'home' == 'home' (true)
5 > 5
or 5 < 7
You’ve probably noticed that we can use variables in conditions
example: x > 23
It’s common practice to make indentations inside a curly braces block of code to make programs more readable. It helps programmers who read the code understand what pieces could be skipped and why.
There is also a way to describe actions for the case when the condition is not true. To do this we should use a special word else. Assume that in our previous program we wanted to print 'SKIPPED' to the screen if the user has canceled file removing. Otherwise, we want to delete the file and print 'DELETED'. In this case, our code would look like this:
if (userAnswer == 'yes') {
deleteFile();
print('DELETED);
} else {
print('SKIPPED);
}