← Back to course

Функции

Функции

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

В предыдущем 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 ты узнаешь:

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

Здесь:

Когда ты 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="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;
    }

    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:

Она должна return:

Hello, NAME!

Пример:

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

const message = createGreeting("Viktor");

console.log(message);

Потом создай another function named checkAccess.

Она должна accept:

Rules:

Пример:

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 с:

Создай эти functions:

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

Когда user clicks button:

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.

Итог

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

Это 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.