← Back to course

Операторы и Условия

Операторы и Условия

С возвращением.

В предыдущем уроке ты изучил variables и data types.

JavaScript теперь может что-то помнить.

Очень impressive.

Сегодня мы научим JavaScript принимать decisions.

Именно здесь code становится интереснее.

До этого JavaScript мог сказать:

“Я знаю price.”

Сегодня JavaScript может сказать:

“Если price слишком high, покажи warning.”

Это большой шаг.

Programs полны decisions:

JavaScript использует operators и conditions, чтобы решить, что должно произойти.

Basically, сегодня JavaScript начинает оценивать situations.

Politely.

Mostly.

Что Ты Изучишь

В этом lesson ты узнаешь:

К концу этого 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="ru">
<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:

Теперь 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.

Почему?

Поэтому JavaScript показывает normal welcome message.

Good.

User enters.

Но без admin powers.

No digital crown today.

Покажи Conditions на Page

Теперь сделаем маленький product availability example.

Обнови index.html:

<!DOCTYPE html>
<html lang="ru">
<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:

Rules:

Пример:

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:

Rules:

Покажи result на page.

Используй:

Bonus:

Добавь different CSS classes для success и warning messages.

Это real-world pattern.

Prices.

Budgets.

Messages.

Conditions.

The web is basically this, but with more meetings.

Итог

Сегодня ты узнал, что:

Это 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 будет тихо плакать.