JavaScript: Conditional statement (if)
Logical expressions let you check various conditions, but on their own they only return true or false. To make a program perform different actions depending on the result, JavaScript has a special construct called if.
if (5 > 3) {
console.log('Yes, it is true');
}Here the string 'Yes, it is true' will be printed because the condition 5 > 3 is true.
┌────────────┐
│ condition? │
└─────┬──────┘
true │
↓
┌────────────┐
│ if body │
└────────────┘Syntax
After if, the condition is written in parentheses, and the body goes in curly braces:
if (condition) {
// the block runs if the condition is true
}A condition is any expression that is coerced to true or false.
Code blocks
Everything inside the curly braces {} belongs to the body of the if. The code after the block runs in any case:
if (10 === 10) {
console.log('First');
console.log('Second');
}
console.log('Goodbye!');Here First and Second will be printed because the condition was met. And Goodbye! is always printed since this line is already outside the block. The principle is the same as in function definitions.
Using if inside a function
Consider a function that determines the type of a given sentence. If it ends with a question mark, the function returns 'question', otherwise — 'normal':
const getTypeOfSentence = (sentence) => {
if (sentence.endsWith('?')) {
return 'question';
}
return 'normal';
};
console.log(getTypeOfSentence('Hodor')); // => normal
console.log(getTypeOfSentence('Hodor?')); // => questionTwo return statements are used here. If the condition inside if is met, return 'question' fires and the function ends. If the condition is not met, control passes to the next line with return 'normal'.
This way, the function has several possible exit points. This is a common practice: depending on the conditions, a function may end in different ways.
Even though the getTypeOfSentence function uses if, it returns strings, which means it is not a predicate. As a predicate, let's consider a function that checks whether there is enough money for a purchase:
const hasEnoughMoney = (balance, price) => {
if (balance >= price) {
return true;
}
return false;
};
console.log(hasEnoughMoney(100, 50)); // => true
console.log(hasEnoughMoney(30, 50)); // => falseif and logical expressions
We wrote the hasEnoughMoney function using if. But in this form it could do without it, because the result of the comparison is itself a logical expression:
const hasEnoughMoney = (balance, price) => balance >= price;In simple cases, it is better to return such an expression right away. if is needed where additional actions are performed inside the block besides returning the result. The more complex the programs, the more often such situations will arise.
Instructions
Write a function guessNumber(guess) that:
- returns
'You win!'ifguess === 42 - returns
'Try again!'otherwise
guessNumber(42); // => 'You win!'
guessNumber(7); // => 'Try again!'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(100500)).toBe('Try again!');
expect(f(42)).toBe('You win!');
});Teacher's solution will be available in:
20:00
