← Back to course

Operatory i Warunki

Operatory i Warunki

Witaj ponownie.

W poprzedniej lekcji nauczyłeś się variables i data types.

JavaScript potrafi już coś zapamiętać.

Bardzo imponujące.

Dzisiaj nauczymy JavaScript podejmować decyzje.

Tutaj code zaczyna być ciekawszy.

Do tej pory JavaScript mógł powiedzieć:

“Znam cenę.”

Dzisiaj JavaScript może powiedzieć:

“Jeśli cena jest za wysoka, pokaż ostrzeżenie.”

To duży krok.

Programy są pełne decyzji:

JavaScript używa operators i conditions, aby zdecydować, co ma się wydarzyć.

Basically, dzisiaj JavaScript zaczyna oceniać sytuacje.

Polite.

Mostly.

Czego Się Nauczysz

W tej lekcji nauczysz się:

Na końcu tej lekcji JavaScript będzie umiał podejmować basic decisions.

Małe decyzje.

Useful decisions.

Nie life decisions.

Proszę, nie pozwalaj jeszcze JavaScript wybierać twojej fryzury.

Stwórz Projekt

Stwórz folder dla tej lekcji:

mkdir javascript-lesson3
cd javascript-lesson3
touch index.html
touch script.js

Twój project powinien wyglądać tak:

javascript-lesson3/
  index.html
  script.js

Otwórz folder w swoim editor.

Najpierw użyjemy console.

Potem pokażemy results na page.

Step by step.

No chaos sprint.

Napisz HTML

Otwórz index.html i dodaj:

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Operatory i Warunki</title>
</head>
<body>
  <h1>Operatory i Warunki</h1>
  <p>Otwórz browser console, aby zobaczyć JavaScript output.</p>

  <script src="script.js"></script>
</body>
</html>

Otwórz file w browser.

Otwórz console:

Teraz JavaScript jest gotowy liczyć i oceniać.

Dangerous combination.

Arithmetic Operators

Arithmetic operators służą do math.

Przykład:

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

Przykład:

const number = 10;

console.log(number % 3);
console.log(2 ** 3);

Output:

1
8

10 % 3 daje 1, bo 10 podzielone przez 3 zostawia remainder 1.

2 ** 3 oznacza 2 do potęgi 3.

Czyli:

2 * 2 * 2 = 8

JavaScript potrafi robić math.

Czasem zbyt szczerze.

Ale potrafi.

Assignment Operators

Znasz już to:

let score = 10;

Symbol = przypisuje value.

Nie oznacza “równa się” jak na matematyce.

Oznacza:

“Włóż tę value do tej variable.”

Przykład:

let score = 10;

score = 20;

console.log(score);

Output:

20

Możesz też aktualizować values używając 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

To są shortcuts.

points += 5;

oznacza:

points = points + 5;

Useful.

Short.

Less typing.

Your fingers approve.

Comparison Operators

Comparison operators porównują values i zwracają true albo false.

Przykład:

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

Przykład:

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 są foundation of conditions.

Pomagają JavaScript decide.

Jeśli answer jest true, zrób coś.

Jeśli answer jest false, zrób coś innego.

Very useful.

Very judgmental.

Różnica między = i ===

To jest ważne.

Bardzo ważne.

Nie pomijaj tego.

= przypisuje value.

const age = 33;

=== porównuje value.

console.log(age === 33);

Przykład:

const age = 33;

console.log(age === 33);
console.log(age === 40);

Output:

true
false

Nie pisz tego w condition:

if (age = 33) {
  console.log("Age is 33");
}

To jest assignment, nie comparison.

Użyj tego:

if (age === 33) {
  console.log("Age is 33");
}

Jedno = oznacza:

“Store this.”

Trzy === oznaczają:

“Compare this.”

Ten błąd jest common.

JavaScript nie zawsze cię uratuje.

JavaScript czasem patrzy, jak upadasz, i mówi:

“Interesting.”

Unikaj == na Razie

JavaScript ma też ==.

Przykład:

console.log(5 == "5");

To zwraca:

true

Dlaczego?

Bo == próbuje convert values przed comparison.

To może być confusing.

Używaj === zamiast tego.

Lepiej:

console.log(5 === "5");

Output:

false

Dlaczego?

Bo jedna value to number, a druga to string.

Dla beginners simple rule:

Używaj ===.

Używaj !==.

Unikaj ==.

Twoje przyszłe debugging sessions będą krótsze.

A kawa zostanie cieplejsza.

if Statement

if statement uruchamia code tylko wtedy, kiedy condition jest true.

Przykład:

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
}

Przykład:

const isLoggedIn = true;

if (isLoggedIn) {
  console.log("Welcome back!");
}

Condition jest true, więc message się pojawia.

Jeśli condition jest false, code w block nie działa.

JavaScript is strict.

No true?

No action.

else Statement

else działa wtedy, kiedy if condition jest false.

Przykład:

const age = 16;

if (age >= 18) {
  console.log("You can enter.");
} else {
  console.log("You are too young.");
}

Output:

You are too young.

To oznacza:

Jeśli age jest greater than or equal to 18, pokaż first message.

Otherwise, pokaż second message.

JavaScript właśnie stał się małym door security guard.

With curly braces.

else if Statement

Użyj else if, kiedy masz więcej niż two possibilities.

Przykład:

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 sprawdza from top to bottom.

First condition:

score >= 90

False.

Second condition:

score >= 60

True.

Więc JavaScript uruchamia ten block i stops.

Nie sprawdza dalej, kiedy znajdzie true condition.

Efficient.

Almost suspiciously efficient.

Logical Operators

Logical operators łączą conditions.

Common logical operators:

&&   and
||   or
!    not

&& oznacza AND

Obie conditions muszą być true.

const age = 25;
const hasTicket = true;

if (age >= 18 && hasTicket) {
  console.log("You can enter.");
}

To oznacza:

Age musi być at least 18.

And user musi mieć ticket.

Both.

No ticket?

No entry.

Nawet jeśli user zrobi do JavaScript smutne oczy.

|| oznacza OR

Przynajmniej jedna condition musi być true.

const isAdmin = false;
const isEditor = true;

if (isAdmin || isEditor) {
  console.log("You can edit this page.");
}

To oznacza:

Jeśli user jest admin OR editor, pozwól na editing.

One true condition is enough.

JavaScript mówi:

“Good enough. Come in.”

! oznacza NOT

! odwraca boolean.

const isLoggedIn = false;

if (!isLoggedIn) {
  console.log("Please log in.");
}

!isLoggedIn oznacza:

“not logged in.”

Ponieważ isLoggedIn jest false, !isLoggedIn staje się true.

Na początku może to feel strange.

Ale jest very useful.

To sposób JavaScript na powiedzenie:

“Actually, the opposite.”

Zbuduj Login Example

Zastąp script.js tym:

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.

Dlaczego?

Więc JavaScript pokazuje normal welcome message.

Good.

User wchodzi.

Ale bez admin powers.

No digital crown today.

Pokaż Conditions na Page

Teraz zrobimy mały product availability example.

Zaktualizuj index.html:

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Operatory i Warunki</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>Operatory i Warunki</h1>

  <div class="card">
    <h2 id="productName"></h2>
    <p id="productPrice"></p>
    <p id="productStatus"></p>
  </div>

  <script src="script.js"></script>
</body>
</html>

Teraz zaktualizuj 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";
}

Odśwież browser.

Powinieneś zobaczyć product information i status message.

Spróbuj zmienić:

const budget = 30;

Potem refresh.

Spróbuj zmienić:

const isAvailable = false;

Refresh again.

Teraz JavaScript pokazuje different messages depending on the data.

To jest real conditional logic.

Page już nie tylko pokazuje information.

Ona decyduje, co pokazać.

Tiny brain unlocked.

Common Mistakes

Używanie = Zamiast ===

Źle:

if (age = 18) {
  console.log("Adult");
}

Dobrze:

if (age === 18) {
  console.log("Adult");
}

One = assigns.

Three === compares.

Tattoo this on your developer soul.

Albo po prostu zapamiętaj.

Less painful.

Zapominanie Curly Braces

Źle:

if (isAvailable)
  console.log("Available");
  console.log("Buy now");

To może być confusing.

Używaj curly braces:

if (isAvailable) {
  console.log("Available");
  console.log("Buy now");
}

Curly braces robią block clear.

Są małe.

Są curly.

Są important.

Conditions w Złej Kolejności

Przykład:

const score = 95;

if (score >= 60) {
  console.log("Good");
} else if (score >= 90) {
  console.log("Excellent");
}

To printuje:

Good

Dlaczego?

Bo score >= 60 jest true, więc JavaScript stops there.

Lepiej:

if (score >= 90) {
  console.log("Excellent");
} else if (score >= 60) {
  console.log("Good");
}

Sprawdzaj more specific conditions first.

JavaScript czyta from top to bottom.

Jak bardzo literal person.

Praktyka

Stwórz variables:

Rules:

Przykład:

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.`);
}

Zmieniaj values i testuj all possible results.

Nie tylko czytaj.

Run it.

Break it.

Fix it.

JavaScript respects action.

Mostly.

Mini Wyzwanie

Stwórz discount calculator.

Variables:

Rules:

Pokaż result na page.

Użyj:

Bonus:

Dodaj różne CSS classes dla success i warning messages.

To jest real-world pattern.

Prices.

Budgets.

Messages.

Conditions.

The web is basically this, but with more meetings.

Podsumowanie

Dzisiaj nauczyłeś się, że:

To major step.

Teraz twój code może choose.

Not perfectly.

Not wisely every time.

But it can choose.

And that is how interactive applications begin.

Następna Lekcja

W następnej lekcji nauczymy się functions.

Functions pomagają reuse code i avoid repeating yourself.

Bo jeśli skopiujesz ten sam code dziesięć razy, JavaScript może go uruchomi.

Ale twój future self będzie cicho płakał.