Оператори та Умови

З поверненням.
У попередньому уроці ти вивчив variables і data types.
JavaScript тепер може щось пам’ятати.
Дуже impressive.
Сьогодні ми навчимо JavaScript приймати decisions.
Саме тут code стає цікавішим.
До цього JavaScript міг сказати:
“Я знаю price.”
Сьогодні JavaScript може сказати:
“Якщо price занадто high, покажи warning.”
Це великий крок.
Programs повні decisions:
- якщо user logged in, покажи dashboard;
- якщо password занадто short, покажи error;
- якщо product available, покажи buy button;
- якщо user натиснув 47 разів, можливо, треба глибоко вдихнути.
JavaScript використовує operators і conditions, щоб вирішити, що має статися.
Basically, сьогодні JavaScript починає оцінювати situations.
Politely.
Mostly.
Що Ти Вивчиш
У цьому lesson ти дізнаєшся:
- arithmetic operators;
- assignment operators;
- comparison operators;
- різницю між
=і===; - як використовувати
if; - як використовувати
else; - як використовувати
else if; - як використовувати logical operators;
- як комбінувати conditions;
- як показувати different messages на page.
До кінця цього lesson JavaScript зможе приймати basic decisions.
Маленькі decisions.
Useful decisions.
Не life decisions.
Будь ласка, не дозволяй JavaScript поки вибирати твою зачіску.
Створи Project
Створи folder для цього lesson:
mkdir javascript-lesson3
cd javascript-lesson3
touch index.html
touch script.js
Твій project має виглядати так:
javascript-lesson3/
index.html
script.js
Відкрий folder у своєму editor.
Спочатку будемо використовувати console.
Потім покажемо results на page.
Step by step.
No chaos sprint.
Напиши HTML
Відкрий index.html і додай:
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Оператори та Умови</title>
</head>
<body>
<h1>Оператори та Умови</h1>
<p>Відкрий browser console, щоб побачити JavaScript output.</p>
<script src="script.js"></script>
</body>
</html>
Відкрий file у browser.
Відкрий console:
- натисни правою кнопкою на page;
- вибери Inspect;
- відкрий tab Console.
Тепер JavaScript готовий рахувати і оцінювати.
Dangerous combination.
Arithmetic Operators
Arithmetic operators використовуються для math.
Приклад:
const a = 10;
const b = 3;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
Output:
13
7
30
3.3333333333333335
Common arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% remainder
** exponentiation
Приклад:
const number = 10;
console.log(number % 3);
console.log(2 ** 3);
Output:
1
8
10 % 3 дає 1, бо 10 поділене на 3 залишає remainder 1.
2 ** 3 означає 2 у степені 3.
Тобто:
2 * 2 * 2 = 8
JavaScript може робити math.
Іноді занадто чесно.
Але може.
Assignment Operators
Ти вже знаєш це:
let score = 10;
Symbol = assigns value.
Він не означає “дорівнює”, як у math class.
Він означає:
“Поклади це value у цю variable.”
Приклад:
let score = 10;
score = 20;
console.log(score);
Output:
20
Можна також update values через shortcut operators:
let points = 10;
points += 5;
console.log(points);
points -= 3;
console.log(points);
points *= 2;
console.log(points);
points /= 4;
console.log(points);
Output:
15
12
24
6
Це shortcuts.
points += 5;
означає:
points = points + 5;
Useful.
Short.
Less typing.
Твої пальці approve.
Comparison Operators
Comparison operators порівнюють values і повертають true або false.
Приклад:
const age = 18;
console.log(age >= 18);
console.log(age < 18);
Output:
true
false
Common comparison operators:
> greater than
< less than
>= greater than or equal to
<= less than or equal to
=== equal value and type
!== not equal value or type
Приклад:
const price = 100;
console.log(price > 50);
console.log(price < 50);
console.log(price === 100);
console.log(price !== 200);
Output:
true
false
true
true
Comparison operators — це foundation of conditions.
Вони допомагають JavaScript decide.
Якщо answer true, зроби щось.
Якщо answer false, зроби щось інше.
Very useful.
Very judgmental.
Різниця між = і ===
Це важливо.
Дуже важливо.
Не пропускай це.
= assigns value.
const age = 33;
=== compares value.
console.log(age === 33);
Приклад:
const age = 33;
console.log(age === 33);
console.log(age === 40);
Output:
true
false
Не пиши це всередині condition:
if (age = 33) {
console.log("Age is 33");
}
Це assignment, не comparison.
Використовуй це:
if (age === 33) {
console.log("Age is 33");
}
Один = означає:
“Store this.”
Три === означають:
“Compare this.”
Ця mistake дуже common.
JavaScript не завжди тебе врятує.
JavaScript іноді дивиться, як ти падаєш, і каже:
“Interesting.”
Поки Уникай ==
У JavaScript також є ==.
Приклад:
console.log(5 == "5");
Це повертає:
true
Чому?
Бо == пробує convert values перед comparison.
Це може бути confusing.
Краще використовуй ===.
console.log(5 === "5");
Output:
false
Чому?
Бо одне value — number, а друге — string.
Для beginners simple rule:
Використовуй ===.
Використовуй !==.
Уникай ==.
Твої future debugging sessions будуть коротшими.
І кава залишиться теплішою.
if Statement
if statement запускає code тільки тоді, коли condition true.
Приклад:
const age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
Output:
You are an adult.
Structure:
if (condition) {
// code runs if condition is true
}
Приклад:
const isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back!");
}
Condition is true, тому message appears.
Якщо condition false, code всередині block не запускається.
JavaScript is strict.
No true?
No action.
else Statement
else запускається тоді, коли if condition false.
Приклад:
const age = 16;
if (age >= 18) {
console.log("You can enter.");
} else {
console.log("You are too young.");
}
Output:
You are too young.
Це означає:
Якщо age greater than or equal to 18, покажи first message.
Otherwise, покажи second message.
JavaScript щойно став маленьким door security guard.
With curly braces.
else if Statement
Використовуй else if, коли маєш більше ніж two possibilities.
Приклад:
const score = 75;
if (score >= 90) {
console.log("Excellent!");
} else if (score >= 60) {
console.log("Good job!");
} else {
console.log("Keep practicing.");
}
Output:
Good job!
JavaScript перевіряє from top to bottom.
First condition:
score >= 90
False.
Second condition:
score >= 60
True.
Тому JavaScript запускає цей block і stops.
Він не продовжує checking після того, як знайшов true condition.
Efficient.
Almost suspiciously efficient.
Logical Operators
Logical operators комбінують conditions.
Common logical operators:
&& and
|| or
! not
&& означає AND
Обидві conditions мають бути true.
const age = 25;
const hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("You can enter.");
}
Це означає:
Age має бути at least 18.
And user має мати ticket.
Both.
No ticket?
No entry.
Навіть якщо user зробить JavaScript сумні очі.
|| означає OR
At least one condition має бути true.
const isAdmin = false;
const isEditor = true;
if (isAdmin || isEditor) {
console.log("You can edit this page.");
}
Це означає:
Якщо user admin OR editor, allow editing.
One true condition is enough.
JavaScript каже:
“Good enough. Come in.”
! означає NOT
! reverses boolean.
const isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in.");
}
!isLoggedIn означає:
“not logged in.”
Оскільки isLoggedIn is false, !isLoggedIn becomes true.
Спочатку це може feel strange.
Але це very useful.
Це спосіб JavaScript сказати:
“Actually, the opposite.”
Побудуй Login Example
Замінити script.js на це:
const userName = "Viktor";
const isLoggedIn = true;
const isAdmin = false;
if (isLoggedIn && isAdmin) {
console.log(`Welcome admin ${userName}.`);
} else if (isLoggedIn) {
console.log(`Welcome ${userName}.`);
} else {
console.log("Please log in.");
}
Output:
Welcome Viktor.
Чому?
isLoggedInis true;isAdminis false;- first condition needs both true;
- second condition needs only
isLoggedIn.
Тому JavaScript показує normal welcome message.
Good.
User enters.
Але без admin powers.
No digital crown today.
Покажи Conditions на Page
Тепер зробимо маленький product availability example.
Онови index.html:
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Оператори та Умови</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 700px;
margin: 60px auto;
padding: 0 24px;
background-color: #f3f4f6;
color: #111827;
}
.card {
background-color: white;
padding: 24px;
border: 2px solid #e5e7eb;
border-radius: 18px;
}
.success {
color: #15803d;
font-weight: 700;
}
.warning {
color: #b45309;
font-weight: 700;
}
h1 {
font-size: 42px;
}
p {
font-size: 20px;
line-height: 1.6;
}
</style>
</head>
<body>
<h1>Оператори та Умови</h1>
<div class="card">
<h2 id="productName"></h2>
<p id="productPrice"></p>
<p id="productStatus"></p>
</div>
<script src="script.js"></script>
</body>
</html>
Тепер онови script.js:
const productName = "JavaScript Course";
const price = 49;
const budget = 60;
const isAvailable = true;
const productNameElement = document.getElementById("productName");
const productPriceElement = document.getElementById("productPrice");
const productStatusElement = document.getElementById("productStatus");
productNameElement.textContent = productName;
productPriceElement.textContent = `Price: €${price}`;
if (isAvailable && price <= budget) {
productStatusElement.textContent = "Good news! This product is available and fits your budget.";
productStatusElement.className = "success";
} else if (isAvailable && price > budget) {
productStatusElement.textContent = "The product is available, but it is over your budget.";
productStatusElement.className = "warning";
} else {
productStatusElement.textContent = "Sorry, this product is not available.";
productStatusElement.className = "warning";
}
Онови browser.
Ти маєш побачити product information і status message.
Спробуй змінити:
const budget = 30;
Потім refresh.
Спробуй змінити:
const isAvailable = false;
Refresh again.
Тепер JavaScript показує different messages depending on the data.
Це real conditional logic.
Page вже не просто показує information.
Вона decides what to show.
Tiny brain unlocked.
Common Mistakes
Використання = Замість ===
Погано:
if (age = 18) {
console.log("Adult");
}
Добре:
if (age === 18) {
console.log("Adult");
}
One = assigns.
Three === compares.
Tattoo this on your developer soul.
Або просто запам’ятай.
Less painful.
Забути Curly Braces
Погано:
if (isAvailable)
console.log("Available");
console.log("Buy now");
Це може бути confusing.
Використовуй curly braces:
if (isAvailable) {
console.log("Available");
console.log("Buy now");
}
Curly braces роблять block clear.
Вони small.
Вони curly.
Вони important.
Conditions у Неправильному Порядку
Приклад:
const score = 95;
if (score >= 60) {
console.log("Good");
} else if (score >= 90) {
console.log("Excellent");
}
Це print:
Good
Чому?
Бо score >= 60 is true, тому JavaScript stops there.
Краще:
if (score >= 90) {
console.log("Excellent");
} else if (score >= 60) {
console.log("Good");
}
Перевіряй more specific conditions first.
JavaScript reads from top to bottom.
Як дуже literal person.
Практика
Створи variables:
- user name;
- age;
- has ticket;
- is VIP.
Rules:
- if user is VIP, show:
Welcome VIP; - else if user is at least 18 and has a ticket, show:
You can enter; - else if user is under 18, show:
You are too young; - else show:
You need a ticket.
Приклад:
const userName = "Anna";
const age = 22;
const hasTicket = true;
const isVip = false;
if (isVip) {
console.log(`Welcome VIP, ${userName}.`);
} else if (age >= 18 && hasTicket) {
console.log(`${userName}, you can enter.`);
} else if (age < 18) {
console.log(`${userName}, you are too young.`);
} else {
console.log(`${userName}, you need a ticket.`);
}
Змінюй values і test all possible results.
Не тільки read it.
Run it.
Break it.
Fix it.
JavaScript respects action.
Mostly.
Міні-Завдання
Створи discount calculator.
Variables:
- product name;
- price;
- user budget;
- discount code active or not.
Rules:
- if discount code is active, reduce the price by 20;
- if final price is less than or equal to budget, show:
You can buy this product; - otherwise show:
This product is too expensive.
Покажи result на page.
Використай:
- variables;
- arithmetic operators;
- comparison operators;
if;else;- template literals;
document.getElementById;textContent.
Bonus:
Додай different CSS classes для success і warning messages.
Це real-world pattern.
Prices.
Budgets.
Messages.
Conditions.
The web is basically this, but with more meetings.
Підсумок
Сьогодні ти дізнався, що:
- arithmetic operators роблять math;
- assignment operators update values;
- comparison operators повертають
trueабоfalse; =assigns value;===compares value and type;!==checks that values are not equal;ifruns code when condition is true;elseruns when condition is false;else ifhandles multiple cases;&&means AND;||means OR;!means NOT;- condition order matters;
- JavaScript can show different content based on data.
Це major step.
Тепер твій code може choose.
Not perfectly.
Not wisely every time.
But it can choose.
And that is how interactive applications begin.
Наступний Урок
У наступному lesson ми вивчимо functions.
Functions допомагають reuse code і avoid repeating yourself.
Бо якщо ти copy той самий code десять разів, JavaScript, можливо, його запустить.
Але твій future self буде тихо плакати.