← Back to course

Funkcje

Funkcje

Witaj ponownie.

W poprzedniej lekcji nauczyłeś JavaScript podejmować decyzje.

JavaScript poznał if, else, comparison operators i logical operators.

Bardzo powerful.

Lekko dangerous.

Dzisiaj nauczymy JavaScript reuse code.

To znaczy, że uczymy się functions.

Functions to jedna z najważniejszych idei w programming.

Function to reusable block of code.

Zamiast pisać ten sam code znowu i znowu, piszesz go raz, nadajesz mu nazwę i call it wtedy, kiedy go potrzebujesz.

Bez functions twój code zamienia się w copy-paste soup.

Z functions twój code staje się cleaner, easier to understand i mniej skłonny do ataku o 2 w nocy.

Bardzo ważne.

Twój future self już szykuje podziękowanie.

Czego Się Nauczysz

W tej lekcji nauczysz się:

Na końcu tej lekcji będziesz umiał organizować JavaScript code w reusable pieces.

To jest duży krok.

Variables remember values.

Conditions make decisions.

Functions create actions you can reuse.

JavaScript powoli staje się cywilizowanym stworzeniem.

Mostly.

Czym Jest Function?

Function to named block of code.

Przykład:

function sayHello() {
  console.log("Hello!");
}

To tworzy function o nazwie sayHello.

Ale samo stworzenie function jej nie uruchamia.

Aby ją uruchomić, musisz ją call:

sayHello();

Pełny przykład:

function sayHello() {
  console.log("Hello!");
}

sayHello();

Output:

Hello!

Pomyśl o function jak o maszynie.

Budujesz machine raz.

Potem naciskasz button, kiedy chcesz, żeby działała.

Very useful.

Szczególnie jeśli machine nie wybucha.

Stwórz Projekt

Stwórz folder dla tej lekcji:

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

Twój project powinien wyglądać tak:

javascript-lesson4/
  index.html
  script.js

Otwórz folder w swoim editor.

Zaczniemy w console.

Potem użyjemy functions, żeby update web page.

Simple.

Clean.

No framework dragon today.

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>Funkcje</title>
</head>
<body>
  <h1>Funkcje</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 ready.

Console patrzy.

Again.

Twoja Pierwsza Function

Otwórz script.js i dodaj:

function greetUser() {
  console.log("Welcome to JavaScript!");
}

greetUser();

Odśwież browser.

Powinieneś zobaczyć:

Welcome to JavaScript!

Co się stało?

function greetUser() {
  console.log("Welcome to JavaScript!");
}

To defines the function.

greetUser();

To calls the function.

Function nie uruchamia się, dopóki jej nie call.

To ważne.

Pisanie function jest jak pisanie recipe.

Calling function jest jak prawdziwe cooking.

Jeśli tylko napiszesz recipe, nikt nie je.

Sad.

But organized.

Calling Function Multiple Times

Możesz call tę samą function więcej niż raz.

function greetUser() {
  console.log("Welcome to JavaScript!");
}

greetUser();
greetUser();
greetUser();

Output:

Welcome to JavaScript!
Welcome to JavaScript!
Welcome to JavaScript!

Code inside function runs every time you call it.

To jest power of functions.

Write once.

Use many times.

Less copy-paste.

Less chaos.

More dignity.

Dlaczego Functions Są Useful

Bez function:

console.log("Welcome, Anna!");
console.log("Welcome, Marco!");
console.log("Welcome, Viktor!");

To działa.

Ale wyobraź sobie robić to w wielu miejscach.

Teraz z function:

function welcomeUser(name) {
  console.log(`Welcome, ${name}!`);
}

welcomeUser("Anna");
welcomeUser("Marco");
welcomeUser("Viktor");

Much better.

Function zawiera logic.

Name się zmienia.

Structure zostaje taka sama.

Tak programmers avoid repeating themselves.

Bo repetition jest OK w exercise.

Ale w code repetition eventually becomes a small monster wearing a hoodie.

Parameters i Arguments

Parameter to variable inside a function.

Argument to actual value, który przekazujesz do function.

Przykład:

function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet("Anna");

Tutaj:

Kiedy call:

greet("Anna");

JavaScript wkłada "Anna" do name.

Potem function używa tej value.

Inny przykład:

function showAge(age) {
  console.log(`You are ${age} years old.`);
}

showAge(33);
showAge(25);

Output:

You are 33 years old.
You are 25 years old.

Parameters sprawiają, że functions są flexible.

Bez parameters, functions robią zawsze to samo.

Z parameters, functions can adapt.

Jak dobre tool.

Albo bardzo polite waiter.

Multiple Parameters

Function może mieć więcej niż jeden parameter.

Przykład:

function introduceUser(firstName, age) {
  console.log(`${firstName} is ${age} years old.`);
}

introduceUser("Viktor", 33);
introduceUser("Anna", 25);

Output:

Viktor is 33 years old.
Anna is 25 years old.

Order matters.

To:

introduceUser("Viktor", 33);

nie jest tym samym co:

introduceUser(33, "Viktor");

JavaScript nie powie:

“Hmm, maybe you meant the opposite.”

On po prostu użyje values w takiej kolejności, jaką mu dałeś.

JavaScript is literal.

Very literal.

Jak robot czytający shopping list.

Return Values

Czasem function nie powinna tylko coś zrobić.

Czasem powinna calculate something i give back a result.

Do tego używamy return.

Przykład:

function addNumbers(a, b) {
  return a + b;
}

const result = addNumbers(5, 3);

console.log(result);

Output:

8

Co się stało?

function addNumbers(a, b) {
  return a + b;
}

Function calculates a + b.

Potem return sends the result back.

const result = addNumbers(5, 3);

Returned value jest zapisana w result.

Important:

return gives a value back from the function.

console.log() only prints something.

To nie jest to samo.

console.log vs return

Ta function prints a value:

function addNumbers(a, b) {
  console.log(a + b);
}

const result = addNumbers(5, 3);

console.log(result);

Output:

8
undefined

Dlaczego undefined?

Bo function printed 8, ale nie returned anything.

Teraz porównaj:

function addNumbers(a, b) {
  return a + b;
}

const result = addNumbers(5, 3);

console.log(result);

Output:

8

Tym razem function returned the value.

Simple rule:

Use console.log() to inspect.

Use return to give a value back.

Console jest dla twoich eyes.

Return jest dla twojego program.

Very different jobs.

Nie myl waiter with kitchen.

Functions z Conditions

Functions mogą używać if, else i else if.

Przykład:

function checkAge(age) {
  if (age >= 18) {
    return "You can enter.";
  } else {
    return "You are too young.";
  }
}

console.log(checkAge(20));
console.log(checkAge(15));

Output:

You can enter.
You are too young.

Ta function receives age.

Potem returns message depending on the age.

To powerful.

Możesz włożyć logic inside functions i reuse it anywhere.

Function staje się małą decision machine.

Hopefully not too judgmental.

Function Expressions

Istnieje też inny sposób tworzenia functions.

const greetUser = function () {
  console.log("Hello!");
};

greetUser();

To nazywa się function expression.

Function jest stored in a variable.

Na razie oba style są useful:

function sayHello() {
  console.log("Hello!");
}

oraz:

const sayHello = function () {
  console.log("Hello!");
};

W tym beginner course będziemy używać głównie pierwszego stylu, bo jest easier to read.

Później często zobaczysz function expressions.

JavaScript ma wiele sposobów na zrobienie tej samej rzeczy.

Bo apparently one way was too peaceful.

Arrow Functions

Modern JavaScript ma też arrow functions.

Przykład:

const greetUser = () => {
  console.log("Hello!");
};

greetUser();

Inny przykład z parameters:

const addNumbers = (a, b) => {
  return a + b;
};

console.log(addNumbers(5, 3));

Arrow functions są common in modern JavaScript.

Zobaczysz je w React, Next.js i wielu innych tools.

Na razie understand the idea:

Arrow function to another way to write a function.

Nie panikuj, jeśli wygląda strange.

To tylko JavaScript wearing modern glasses.

Zbuduj Price Calculator

Teraz zbudujemy małą function, która calculates final price.

Zastąp script.js tym:

function calculateFinalPrice(price, discount) {
  return price - discount;
}

const coursePrice = 49;
const courseDiscount = 10;

const finalPrice = calculateFinalPrice(coursePrice, courseDiscount);

console.log(`Final price: €${finalPrice}`);

Output:

Final price: €39

To useful, bo calculation is reusable.

Możesz calculate many prices:

function calculateFinalPrice(price, discount) {
  return price - discount;
}

console.log(calculateFinalPrice(49, 10));
console.log(calculateFinalPrice(100, 25));
console.log(calculateFinalPrice(80, 15));

Output:

39
75
65

One function.

Many results.

That is the magic.

Not real magic.

Better.

Debuggable magic.

Functions and the DOM

Teraz użyjemy functions z HTML.

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>Funkcje</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;
    }

    button {
      background-color: #2563eb;
      color: white;
      border: none;
      padding: 14px 20px;
      border-radius: 999px;
      font-weight: 700;
      cursor: pointer;
    }

    button:hover {
      background-color: #1d4ed8;
    }

    .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>Funkcje</h1>

  <div class="card">
    <h2 id="productName">JavaScript Course</h2>
    <p id="productPrice">Price: €49</p>
    <p id="productStatus">Click the button to check the discount.</p>
    <button id="checkButton">Check Discount</button>
  </div>

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

Teraz zaktualizuj script.js:

const productStatusElement = document.getElementById("productStatus");
const checkButton = document.getElementById("checkButton");

function calculateFinalPrice(price, discount) {
  return price - discount;
}

function showPriceMessage() {
  const price = 49;
  const discount = 10;
  const budget = 45;

  const finalPrice = calculateFinalPrice(price, discount);

  if (finalPrice <= budget) {
    productStatusElement.textContent = `Good news! Final price is €${finalPrice}. You can buy it.`;
    productStatusElement.className = "success";
  } else {
    productStatusElement.textContent = `Final price is €${finalPrice}. It is over your budget.`;
    productStatusElement.className = "warning";
  }
}

checkButton.addEventListener("click", showPriceMessage);

Odśwież browser.

Kliknij button.

JavaScript runs the function.

Function calculates final price.

Then it shows a message on the page.

To bardzo blisko real web development.

User action.

Function runs.

Data changes.

Page updates.

Beautiful.

Browser już nie siedzi tam jak decorative potato.

Jak Działa Ten Code

To znajduje paragraph:

const productStatusElement = document.getElementById("productStatus");

To znajduje button:

const checkButton = document.getElementById("checkButton");

Ta function calculates final price:

function calculateFinalPrice(price, discount) {
  return price - discount;
}

Ta function updates the page:

function showPriceMessage() {
  const price = 49;
  const discount = 10;
  const budget = 45;

  const finalPrice = calculateFinalPrice(price, discount);

  if (finalPrice <= budget) {
    productStatusElement.textContent = `Good news! Final price is €${finalPrice}. You can buy it.`;
    productStatusElement.className = "success";
  } else {
    productStatusElement.textContent = `Final price is €${finalPrice}. It is over your budget.`;
    productStatusElement.className = "warning";
  }
}

To łączy button click z function:

checkButton.addEventListener("click", showPriceMessage);

Zauważ coś important:

Piszemy:

showPriceMessage

nie:

showPriceMessage()

Dlaczego?

Bo chcemy, żeby JavaScript uruchomił function later, kiedy button is clicked.

Jeśli napiszesz showPriceMessage(), function runs immediately.

To common beginner mistake.

JavaScript is very literal.

Again.

Common Mistakes

Forgetting to Call the Function

Źle:

function sayHello() {
  console.log("Hello!");
}

To defines function, ale jej nie runs.

Dobrze:

function sayHello() {
  console.log("Hello!");
}

sayHello();

Functions nie uruchamiają się same.

Nie są cats.

Nie decydują randomowo, że coś zrobią.

Usually.

Confusing Parameters and Arguments

function greet(name) {
  console.log(`Hello, ${name}`);
}

greet("Anna");

name is the parameter.

"Anna" is the argument.

Parameter is the placeholder.

Argument is the real value.

Simple.

Powerful.

Slightly fancy words.

Forgetting return

Źle:

function add(a, b) {
  a + b;
}

const result = add(2, 3);

console.log(result);

Output:

undefined

Dobrze:

function add(a, b) {
  return a + b;
}

Jeśli chcesz, żeby function give back a value, użyj return.

JavaScript will not guess.

JavaScript does not do emotional interpretation.

Calling a Function Too Early in an Event Listener

Źle:

button.addEventListener("click", showMessage());

Dobrze:

button.addEventListener("click", showMessage);

Without parentheses, you pass the function.

With parentheses, you call it immediately.

To jest important.

Very important.

This bug loves beginners.

Do not feed it.

Praktyka

Stwórz function named createGreeting.

Powinna accept one parameter:

Powinna return:

Hello, NAME!

Przykład:

function createGreeting(name) {
  return `Hello, ${name}!`;
}

const message = createGreeting("Viktor");

console.log(message);

Potem stwórz another function named checkAccess.

Powinna accept:

Rules:

Przykład:

function checkAccess(age, hasTicket) {
  if (age >= 18 && hasTicket) {
    return "Access granted";
  }

  return "Access denied";
}

console.log(checkAccess(22, true));
console.log(checkAccess(16, true));
console.log(checkAccess(30, false));

Run it.

Change values.

Break it.

Fix it.

Tak functions stają się normalne.

Mini Wyzwanie

Zbuduj małą page z:

Stwórz te functions:

function calculateFinalPrice(price, discount) {
  return price - discount;
}
function createPriceMessage(finalPrice) {
  return `The final price is €${finalPrice}.`;
}

Kiedy user clicks button:

Bonus:

Dodaj budget.

Jeśli final price is less than or equal to budget, pokaż success message.

Otherwise, pokaż warning message.

This is exactly how real websites work.

Small functions.

Clear responsibilities.

Clean logic.

Less spaghetti.

More lasagna.

Structured layers.

Very Italy-friendly code.

Podsumowanie

Dzisiaj nauczyłeś się, że:

To huge step.

Functions są wszędzie w JavaScript.

Kiedy rozumiesz functions, language becomes much easier to organize.

Bez functions code becomes a messy drawer.

Z functions code becomes a toolbox.

Still messy sometimes.

Ale przynajmniej hammer has a place.

Następna Lekcja

W następnej lekcji nauczymy się arrays.

Arrays pomagają store lists of values.

Names.

Products.

Tasks.

Scores.

Basically, kiedy one variable is not enough, arrays arrive.

With brackets.

And opinions.