Conditional statements control the program's behavior depending on the conditions we want to test. They allow us to write complex programs that behave differently depending on the situation.
if
Consider a function to which we can pass a sentence and determine what type of sentence it is. To begin with, it will distinguish between normal sentences and question sentences.
const getTypeOfSentence = (sentence) => {
const lastChar = sentence[sentence.length - 1];
if (lastChar === '?') {
return 'question';
}
return 'general';
};
getTypeOfSentence('Hodor'); // general
getTypeOfSentence('Hodor?'); // question
if is a construct that maintains the procedure by which statements are executed. You need to pass predicate expression to it in parentheses and then define a block of code in curly brackets. This code block executes only if the predicate is true.
If the predicate is false, we skip the code block in curly brackets, and the function keeps executing. Here, the next line of code, return 'general';, causes the function to return a string and terminate.
As you can see, return can be anywhere in a function. Including the interior of a conditional code block.
If the curly brackets after if contains only one line of code, you can leave out the brackets:
const getTypeOfSentence = (sentence) => {
const lastChar = sentence[sentence.length - 1];
if (lastChar === '?')
return 'question';
return 'general';
};
console.log(getTypeOfSentence('Hodor')); // => general
console.log(getTypeOfSentence('Hodor?')); // => question
We advise against it and to always use curly brackets. That way you can clearly see where the conditional's body starts and ends. The code becomes clearer and more readable.
else
Let's write a function getTypeOfSentence() to analyze a piece of text and return its type: General sentence for normal sentences and Question sentence for questions.
getTypeOfSentence('Hodor'); // General sentence
getTypeOfSentence('Hodor?'); // Question sentence
Implementation:
const getTypeOfSentence = (sentence) => {
// Declare a variable to store the sentence type
let sentenceType;
// Predicate checking the text ending
// If it ends with '?', it will return true,
// otherwise, it'll return false
if (sentence.endsWith('?')) {
// If the condition above holds true,
// we have a question sentence.
// Assign an appropriate value to sentenceType
sentenceType = 'Question';
} else {
// Otherwise, the sentenceType is 'General'
sentenceType = 'General';
}
// Build a string via interpolation
return `${sentenceType} sentence`;
};
We have added the keyword else and a new block with curly brackets. This block executes only if the condition in if is false.
There are two ways to design an if-else clause. The negation allows you to change the order of the blocks:
const getTypeOfSentence = (sentence) => {
let sentenceType;
// Add negation
// The code blocks with the 'else' and 'if' statements are swapped
if (!sentence.endsWith('?')) {
sentenceType = 'General';
} else {
sentenceType = 'Question';
}
return `${sentenceType} sentence`;
};
Which way is preferable? It is easier for the human brain to reason in a straightforward manner rather than via negation. Try to pick a test that has no negations, and then modify the contents of the code blocks to suit it.
else if construction
The getTypeOfSentence() function from the previous lesson only distinguishes between questions and normal sentences. Let's try to extend it to exclamation sentences:
const getTypeOfSentence = (sentence) => {
const lastChar = sentence[sentence.length - 1];
let sentenceType;
if (lastChar === '!') {
sentenceType = 'exclamation';
} else {
sentenceType = 'normal';
}
if (lastChar === '?') {
sentenceType = 'question';
}
return `Sentence is ${sentenceType}`;
};
getTypeOfSentence('Who?'); // 'Sentence is question'
getTypeOfSentence('No'); // 'Sentence is normal'
getTypeOfSentence('No!'); // 'Sentence is exclamation'
We added one more test. Technically the function works, but there are semantics issues.
- It tests for the question mark in any case, regardless of whether an exclamation point was found or not
- The
elsebranch is defined for the first condition, not for the second
It would be better to use another condition feature:
const getTypeOfSentence = (sentence) => {
const lastChar = sentence[sentence.length - 1];
let sentenceType;
if (lastChar === '?') {
sentenceType = 'question';
} else if (lastChar === '!') {
sentenceType = 'exclamation';
} else {
sentenceType = 'normal';
}
return `Sentence is ${sentenceType}`;
};
getTypeOfSentence('Who?'); // 'Sentence is question'
getTypeOfSentence('No'); // 'Sentence is normal'
getTypeOfSentence('No!'); // 'Sentence is exclamation'
Now all the conditions are framed in a single construction. else if means "if the previous condition is not satisfied, but this condition is". This is the scenario we get:
- if the last character is
?, then it's a'question' - else, if the last character is
!, then it's an'exclamation' - else it's
'normal'
Only one of the code blocks belonging to the entire if construct will be executed.