JavaScript: else if statement
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'
https://replit.com/@hexlet/js-basics-conditionals
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
else
branch 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.
Instructions
The digital map of Westeros that Sam has made shows Stark allies in green, enemies in red, and neutral families in gray.
Write the whoIsThisHouseToStarks()
function that takes a family name as input and returns one of three values: 'friend'
, 'enemy'
, 'neutral'
.
Rules:
- Friends: 'Karstark', 'Tally'
- Enemies: 'Lannister', 'Frey'
- Any other families are considered neutral
Examples:
whoIsThisHouseToStarks('Karstark'); // 'friend'
whoIsThisHouseToStarks('Frey'); // 'enemy'
whoIsThisHouseToStarks('Joar'); // 'neutral'
whoIsThisHouseToStarks('Ivanov'); // 'neutral'
Definitions
else if is a way to set multiple alternate conditions