Функції

З поверненням.
У попередньому lesson ти навчив JavaScript приймати decisions.
JavaScript вивчив if, else, comparison operators і logical operators.
Дуже powerful.
Трохи dangerous.
Сьогодні ми навчимо JavaScript reuse code.
Тобто ми вивчаємо functions.
Functions — це одна з найважливіших ідей у programming.
Function — це reusable block of code.
Замість того щоб писати той самий code знову і знову, ти пишеш його один раз, даєш йому name і викликаєш, коли він тобі потрібен.
Без functions твій code перетворюється на copy-paste soup.
З functions твій code стає cleaner, easier to understand і менше схожий на щось, що нападе на тебе о 2 ночі.
Дуже важливо.
Твій future self уже готується подякувати тобі.
Що Ти Вивчиш
У цьому lesson ти дізнаєшся:
- що таке functions;
- як створити function;
- як call a function;
- як працюють parameters;
- як працюють arguments;
- як return values;
- як avoid repeated code;
- як functions працюють з conditions;
- як використовувати functions з DOM;
- як побудувати маленький price calculator.
До кінця цього lesson ти зможеш organize JavaScript code у reusable pieces.
Це major step.
Variables remember values.
Conditions make decisions.
Functions create actions you can reuse.
JavaScript повільно стає civilized creature.
Mostly.
Що Таке Function?
Function — це named block of code.
Приклад:
function sayHello() {
console.log("Hello!");
}
Це створює function з назвою sayHello.
Але створення function не запускає її.
Щоб запустити function, її треба call:
sayHello();
Повний приклад:
function sayHello() {
console.log("Hello!");
}
sayHello();
Output:
Hello!
Думай про function як про machine.
Ти будуєш machine один раз.
Потім натискаєш button, коли хочеш, щоб вона працювала.
Very useful.
Особливо якщо machine не вибухає.
Створи Project
Створи folder для цього lesson:
mkdir javascript-lesson4
cd javascript-lesson4
touch index.html
touch script.js
Твій project має виглядати так:
javascript-lesson4/
index.html
script.js
Відкрий folder у своєму editor.
Ми почнемо в console.
Потім використаємо functions, щоб update web page.
Simple.
Clean.
No framework dragon today.
Напиши 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 ready.
Console дивиться.
Again.
Твоя Перша Function
Відкрий script.js і додай:
function greetUser() {
console.log("Welcome to JavaScript!");
}
greetUser();
Онови browser.
Ти маєш побачити:
Welcome to JavaScript!
Що сталося?
function greetUser() {
console.log("Welcome to JavaScript!");
}
Це defines the function.
greetUser();
Це calls the function.
Function не запускається, поки ти її не call.
Це важливо.
Writing a function — це як писати recipe.
Calling a function — це як actually cooking.
Якщо ти тільки написав recipe, ніхто не їсть.
Sad.
But organized.
Calling Function Multiple Times
Ти можеш call одну і ту саму function багато разів.
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.
Це power of functions.
Write once.
Use many times.
Less copy-paste.
Less chaos.
More dignity.
Чому Functions Useful
Без function:
console.log("Welcome, Anna!");
console.log("Welcome, Marco!");
console.log("Welcome, Viktor!");
Це працює.
Але уяви, що ти робиш це у багатьох places.
Тепер з function:
function welcomeUser(name) {
console.log(`Welcome, ${name}!`);
}
welcomeUser("Anna");
welcomeUser("Marco");
welcomeUser("Viktor");
Much better.
Function містить logic.
Name змінюється.
Structure залишається same.
Так programmers avoid repeating themselves.
Бо repetition нормальна в exercises.
Але в code repetition eventually becomes a small monster wearing a hoodie.
Parameters і Arguments
Parameter — це variable inside a function.
Argument — це actual value, яке ти передаєш у function.
Приклад:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Anna");
Тут:
nameis the parameter;"Anna"is the argument.
Коли ти call:
greet("Anna");
JavaScript кладе "Anna" у name.
Потім function використовує цю value.
Інший приклад:
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 роблять functions flexible.
Без parameters functions завжди роблять same thing.
З parameters functions can adapt.
Як good tool.
Або very polite waiter.
Multiple Parameters
Function може мати більше ніж один parameter.
Приклад:
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.
Це:
introduceUser("Viktor", 33);
не те саме, що це:
introduceUser(33, "Viktor");
JavaScript не скаже:
“Hmm, maybe you meant the opposite.”
Він просто використає values у тому order, у якому ти їх дав.
JavaScript is literal.
Very literal.
Як robot, який читає shopping list.
Return Values
Іноді function має не тільки щось зробити.
Іноді вона має calculate something і give back a result.
Для цього використовуємо return.
Приклад:
function addNumbers(a, b) {
return a + b;
}
const result = addNumbers(5, 3);
console.log(result);
Output:
8
Що сталося?
function addNumbers(a, b) {
return a + b;
}
Function calculates a + b.
Потім return sends the result back.
const result = addNumbers(5, 3);
Returned value зберігається у result.
Important:
return gives a value back from the function.
console.log() only prints something.
Це не одне й те саме.
console.log vs return
Ця function prints a value:
function addNumbers(a, b) {
console.log(a + b);
}
const result = addNumbers(5, 3);
console.log(result);
Output:
8
undefined
Чому undefined?
Бо function printed 8, але не returned anything.
Тепер порівняй:
function addNumbers(a, b) {
return a + b;
}
const result = addNumbers(5, 3);
console.log(result);
Output:
8
Цього разу function returned the value.
Simple rule:
Use console.log() to inspect.
Use return to give a value back.
Console — для твоїх eyes.
Return — для твоєї program.
Very different jobs.
Не плутай waiter with kitchen.
Functions з Conditions
Functions можуть використовувати if, else і else if.
Приклад:
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.
Ця function receives age.
Потім returns message depending on the age.
Це powerful.
Ти можеш покласти logic inside functions і reuse it anywhere.
Function стає маленькою decision machine.
Hopefully not too judgmental.
Function Expressions
Є ще інший спосіб створити functions.
const greetUser = function () {
console.log("Hello!");
};
greetUser();
Це називається function expression.
Function stored in a variable.
Поки що обидва styles useful:
function sayHello() {
console.log("Hello!");
}
і:
const sayHello = function () {
console.log("Hello!");
};
У цьому beginner course ми mostly будемо використовувати перший style, бо він easier to read.
Пізніше ти часто побачиш function expressions.
JavaScript має багато способів зробити same thing.
Бо apparently one way was too peaceful.
Arrow Functions
Modern JavaScript також має arrow functions.
Приклад:
const greetUser = () => {
console.log("Hello!");
};
greetUser();
Інший приклад з parameters:
const addNumbers = (a, b) => {
return a + b;
};
console.log(addNumbers(5, 3));
Arrow functions common in modern JavaScript.
Ти побачиш їх у React, Next.js і багатьох other tools.
Поки що understand the idea:
Arrow function — це another way to write a function.
Не panic, якщо вона виглядає strange.
Це просто JavaScript wearing modern glasses.
Побудуй Price Calculator
Тепер побудуємо маленьку function, яка calculates final price.
Замінити script.js на це:
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
Це useful, бо calculation reusable.
Можна 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
Тепер використаємо functions з 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>
<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>Функції</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>
Тепер онови 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);
Онови browser.
Натисни button.
JavaScript runs the function.
Function calculates final price.
Then it shows a message on the page.
Це дуже близько до real web development.
User action.
Function runs.
Data changes.
Page updates.
Beautiful.
Browser уже не просто сидить там як decorative potato.
Як Працює Цей Code
Це знаходить paragraph:
const productStatusElement = document.getElementById("productStatus");
Це знаходить button:
const checkButton = document.getElementById("checkButton");
Ця function calculates final price:
function calculateFinalPrice(price, discount) {
return price - discount;
}
Ця 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";
}
}
Це connects button click to the function:
checkButton.addEventListener("click", showPriceMessage);
Зверни увагу на important detail:
Ми пишемо:
showPriceMessage
а не:
showPriceMessage()
Чому?
Бо ми хочемо, щоб JavaScript run the function later, коли button clicked.
Якщо написати showPriceMessage(), function runs immediately.
Це common beginner mistake.
JavaScript is very literal.
Again.
Common Mistakes
Forgetting to Call the Function
Погано:
function sayHello() {
console.log("Hello!");
}
Це defines function, але не runs it.
Добре:
function sayHello() {
console.log("Hello!");
}
sayHello();
Functions do not run by themselves.
They are not cats.
They do not randomly decide to do things.
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
Погано:
function add(a, b) {
a + b;
}
const result = add(2, 3);
console.log(result);
Output:
undefined
Добре:
function add(a, b) {
return a + b;
}
Якщо хочеш, щоб function give back a value, використовуй return.
JavaScript will not guess.
JavaScript does not do emotional interpretation.
Calling a Function Too Early in an Event Listener
Погано:
button.addEventListener("click", showMessage());
Добре:
button.addEventListener("click", showMessage);
Without parentheses, you pass the function.
With parentheses, you call it immediately.
Це important.
Very important.
This bug loves beginners.
Do not feed it.
Практика
Створи function named createGreeting.
Вона має accept one parameter:
name
Вона має return:
Hello, NAME!
Приклад:
function createGreeting(name) {
return `Hello, ${name}!`;
}
const message = createGreeting("Viktor");
console.log(message);
Потім створи another function named checkAccess.
Вона має accept:
age;hasTicket.
Rules:
- if age is at least 18 and hasTicket is true, return
Access granted; - otherwise return
Access denied.
Приклад:
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.
Так functions стають normal.
Міні-Завдання
Побудуй маленьку page з:
- product name;
- price;
- discount;
- button;
- message area.
Створи ці functions:
function calculateFinalPrice(price, discount) {
return price - discount;
}
function createPriceMessage(finalPrice) {
return `The final price is €${finalPrice}.`;
}
Коли user clicks button:
- calculate final price;
- create message;
- show message on the page.
Bonus:
Додай budget.
Якщо final price is less than or equal to budget, покажи success message.
Otherwise, покажи 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.
Підсумок
Сьогодні ти дізнався, що:
- functions are reusable blocks of code;
- functions must be called to run;
- parameters are placeholders inside functions;
- arguments are real values passed into functions;
- functions can return values;
returngives a value back;console.log()only prints a value;- functions can contain conditions;
- functions can update the DOM;
- functions help avoid repeated code;
- event listeners can run functions when users interact.
Це huge step.
Functions всюди в JavaScript.
Коли ти розумієш functions, language стає much easier to organize.
Без functions code becomes a messy drawer.
З functions code becomes a toolbox.
Still messy sometimes.
Але принаймні hammer has a place.
Наступний Урок
У наступному lesson ми вивчимо arrays.
Arrays допомагають store lists of values.
Names.
Products.
Tasks.
Scores.
Basically, коли one variable is not enough, arrays arrive.
With brackets.
And opinions.