JavaScript: else
Let's write a function getTypeOfSentence() that analyzes text and returns a description of its tone: for ordinary sentences – General sentence, for interrogative ones – Question sentence.
getTypeOfSentence('Hodor'); // General sentence
getTypeOfSentence('Hodor?'); // Question sentenceThe function implementation:
const getTypeOfSentence = (sentence) => {
// Declare a variable to store the sentence type
let sentenceType;
// A predicate that checks the end of the text
// If it ends with the '?' character, it returns true,
// otherwise false
if (sentence.endsWith('?')) {
// If the condition above was met,
// then this is an interrogative sentence.
// Assign the corresponding value to sentenceType.
sentenceType = 'Question';
} else {
// In all other cases the sentence is a general one
sentenceType = 'General';
}
// Using interpolation we build a string
return `${sentenceType} sentence`;
};We added the keyword else and a new block with curly braces. This block runs only if the condition in if is false.
┌───────────┐
│ condition?│
└─────┬─────┘
true │ │ false
↓ ↓
┌──────────┐ ┌──────────┐
│ if body │ │ else body│
└──────────┘ └──────────┘Nested conditions
Inside the else block (just like inside the if block) you can nest other conditions. Thanks to the curly braces, the nesting is always explicitly visible:
const number = 10;
if (number > 10) {
console.log('Number is greater than 10');
} else {
if (number === 10) {
console.log('Number is exactly 10');
} else {
console.log('Number is less than 10');
}
}
// => Number is exactly 10Here number > 10 is checked first. The condition is false, so control passes to else, where the nested condition number === 10 is checked. It is true — Number is exactly 10 is printed.
There are two ways to lay out an if-else construct. Using negation, you can swap the order of the blocks:
const getTypeOfSentence = (sentence) => {
let sentenceType;
// A negation was added
// The contents of else moved to if and vice versa
if (!sentence.endsWith('?')) {
sentenceType = 'General';
} else {
sentenceType = 'Question';
}
return `${sentenceType} sentence`;
};Which way is preferable? The human brain finds it easier to think in a straightforward way rather than through negation. Try to choose a check that does not contain negations, and adjust the contents of the blocks to fit it.
Instructions
Write a function normalizeUrl(url) that takes a string with a website address and returns a URL with the https:// protocol.
If the string already starts with https:// — return it as is. If it does not start with it — add https:// at the beginning.
normalizeUrl('https://hexlet.io'); // => 'https://hexlet.io'
normalizeUrl('hexlet.io'); // => 'https://hexlet.io'Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
import { expect, test } from 'vitest';
import f from './index.js';
test('test', () => {
expect(f('yandex.ru')).toBe('https://yandex.ru');
expect(f('https://yandex.ru')).toBe('https://yandex.ru');
});Teacher's solution will be available in:
20:00
