Skip to content
Merged
Changes from 2 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
2657e40
Functions (#127)
hypeofpipe Jul 13, 2021
70d7220
Translate 'Parameters'
tarasyyyk Jul 13, 2021
b5037dc
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Jul 21, 2021
c3baaa4
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Jul 21, 2021
d6836ea
Translate 'default values'
tarasyyyk Aug 2, 2021
09129f1
Merge branch 'function-basics' of github.com:javascript-tutorial/uk.j…
tarasyyyk Aug 2, 2021
4a323cb
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
c81076a
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
3b15e47
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
b3ee6b3
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
90a0055
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
2f752e7
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
75bdab2
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
2927bdf
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
a9c06b2
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
8fa0670
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
998c089
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
c81cd91
Merge branch 'master' into function-basics
tarasyyyk Aug 4, 2021
c9a4759
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
551e343
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 4, 2021
d13a0a5
Translate 'Alternative default parameters'
tarasyyyk Aug 4, 2021
63a71ac
Fix lines
tarasyyyk Aug 4, 2021
69b1d4e
Translate 'Returning value'
tarasyyyk Aug 8, 2021
5e69205
Translate 'Naming a function'
tarasyyyk Aug 10, 2021
a92a590
Translate 'Functions == Comments'
tarasyyyk Aug 11, 2021
bbef865
Translate 'Summary'
tarasyyyk Aug 12, 2021
49c7498
Translate tasks
tarasyyyk Aug 12, 2021
35a7e7b
Small correction
tarasyyyk Aug 12, 2021
d8b912e
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
c04547d
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
c593e1c
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
d7782b5
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
94edb76
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
e07b2db
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
da2c2b9
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
fade570
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
061af87
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
8c7507d
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
24f31a2
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
f866d6a
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk Aug 12, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 77 additions & 76 deletions 1-js/02-first-steps/15-function-basics/article.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
# Functions
# Функції

Quite often we need to perform a similar action in many places of the script.
Досить часто нам потрібно виконати подібну дію в багатьох місцях скрипту.

For example, we need to show a nice-looking message when a visitor logs in, logs out and maybe somewhere else.
Наприклад, нам треба показати приємне повідомлення, коли користувач входить або виходить з системи і може ще десь.

Functions are the main "building blocks" of the program. They allow the code to be called many times without repetition.
Функції — це головні "будівельні блоки" програми. Вони дозволяють робити ті самі дії багато разів в коді без повторення.

We've already seen examples of built-in functions, like `alert(message)`, `prompt(message, default)` and `confirm(question)`. But we can create functions of our own as well.
Ми вже стикались з такими вбудованими функціями, як-от `alert(message)`, `prompt(message, default)` та `confirm(question)`. Але ми теж можемо створювати свої функції.

## Function Declaration
## Оголошення (декларація) функцій

To create a function we can use a *function declaration*.
Щоб створити функцію нам треба її _оголосити_.

It looks like this:
Це виглядає ось так:

```js
function showMessage() {
alert( 'Hello everyone!' );
alert('Всім привіт!');
}
```

The `function` keyword goes first, then goes the *name of the function*, then a list of *parameters* between the parentheses (comma-separated, empty in the example above, we'll see examples later) and finally the code of the function, also named "the function body", between curly braces.
Спочатку ми пишемо `function` — це ключове слово (keyword), яке дає зрозуміти комп’ютеру, що далі буде оголошення функції. Потім — *назву функції*, тоді список її *параметрів* в дужках (розділені комою). Якщо параметрів немає, ми залишаємо _пусті дужки_. І нарешті, код функції, який також називають *тілом функції* між фігурними дужками.

```js
function name(parameter1, parameter2, ... parameterN) {
...body...
...тіло функції...
}
```

Our new function can be called by its name: `showMessage()`.
Нашу нову функцію можна викликати, написавши її ім’я і дужки: `showMessage()`.

For instance:
Наприклад:

```js run
function showMessage() {
alert( 'Hello everyone!' );
alert( 'Шановні друзі!' );
}

*!*
Expand All @@ -43,145 +43,145 @@ showMessage();
*/!*
```

The call `showMessage()` executes the code of the function. Here we will see the message two times.
Виклик `showMessage()` виконує код із тіла функції. В цьому випадку, ми побачимо повідомлення двічі.

This example clearly demonstrates one of the main purposes of functions: to avoid code duplication.
Цей приклад яскраво демонструє одну з найголовніших цілей функції - уникнення повторення коду.

If we ever need to change the message or the way it is shown, it's enough to modify the code in one place: the function which outputs it.
Якщо нам потрібно змінити повідомлення, достатньо змінити тіло функції, яке виводить це повідомлення.

## Local variables
## Локальні змінні

A variable declared inside a function is only visible inside that function.
Змінна, яка оголошена в функції доступна лише в тілі цієї функції.

For example:
До прикладу:

```js run
function showMessage() {
*!*
let message = "Hello, I'm JavaScript!"; // local variable
let message = "Бажаю вам 36.6"; // локальна змінна
*/!*

alert( message );
}

showMessage(); // Hello, I'm JavaScript!
showMessage(); // Бажаю вам 36.6

alert( message ); // <-- Error! The variable is local to the function
alert( message ); // <-- Помилка! Змінна недоступна поза функцією
```

## Outer variables
## Зовнішні змінні

A function can access an outer variable as well, for example:
Функція може використовувати зовнішні змінні, наприклад:

```js run no-beautify
let *!*userName*/!* = 'John';
let *!*userName*/!* = 'Іван';

function showMessage() {
let message = 'Hello, ' + *!*userName*/!*;
let message = 'Привіт, ' + *!*userName*/!*;
alert(message);
}

showMessage(); // Hello, John
showMessage(); // Привіт, Іван
```

The function has full access to the outer variable. It can modify it as well.
Функція має повний доступ до зовнішньої змінної. Вона теж може її змінювати.

For instance:
Наприклад:

```js run
let *!*userName*/!* = 'John';
let *!*userName*/!* = 'Іван';

function showMessage() {
*!*userName*/!* = "Bob"; // (1) changed the outer variable
*!*userName*/!* = "Богдан"; // (1) змінено зовнішню змінну

let message = 'Hello, ' + *!*userName*/!*;
let message = 'Здоровенькі були, ' + *!*userName*/!*;
alert(message);
}

alert( userName ); // *!*John*/!* before the function call
alert( userName ); // *!*Іван*/!* перед викликом функції showMessage

showMessage();

alert( userName ); // *!*Bob*/!*, the value was modified by the function
alert( userName ); // *!*Богдан*/!*, значення було змінено після виклику функції showMessage
```

The outer variable is only used if there's no local one.
Зовнішня змінна використовується тоді, коли немає локальної.

If a same-named variable is declared inside the function then it *shadows* the outer one. For instance, in the code below the function uses the local `userName`. The outer one is ignored:
Якщо всередині функції є змінна з таким самим ім’ям, то вона *затьмарює* зовнішню. Наприклад, наступний код використовує локальну змінну `userName`. Зовнішня ігнорується.

```js run
let userName = 'John';
let userName = 'Іван'; // оголошення зовнішньої змінної

function showMessage() {
*!*
let userName = "Bob"; // declare a local variable
let userName = "Богдан"; // оголошення локальної змінної
*/!*

let message = 'Hello, ' + userName; // *!*Bob*/!*
let message = 'Привіт, ' + userName; // *!*Богдан*/!*
alert(message);
}

// the function will create and use its own userName
// функція завжди віддасть перевагу локальним змінним
showMessage();

alert( userName ); // *!*John*/!*, unchanged, the function did not access the outer variable
alert( userName ); // *!*Іван*/!*, без змін, функція не змінила глобальну змінну
```

```smart header="Global variables"
Variables declared outside of any function, such as the outer `userName` in the code above, are called *global*.
```smart header="Глобальні змінні"
Змінні, оголошені поза будь-якими функціями (такі як зовнішня зміння `userName` з коду вище), називаються *глобальні* змінні.

Global variables are visible from any function (unless shadowed by locals).
Глобальні змінні доступні в будь-якій функції (окрім випадків, коли глобальна змінна затьмарена локальною).

It's a good practice to minimize the use of global variables. Modern code has few or no globals. Most variables reside in their functions. Sometimes though, they can be useful to store project-level data.
Хорошою практикою вважається мінімізація використання глобальних змінних. У сучасному коді є декалька або одна глобальна змінна. Більшість змінних знаходяться в межах функцій. Іноді, буває корисно зберігати "загальні" дані (на рівні проєкту) в таких глобальних змінних.
```

## Parameters
## Параметри

We can pass arbitrary data to functions using parameters.
Ми можемо передати в функцію довільні дані використовуючи параметри.

In the example below, the function has two parameters: `from` and `text`.
В наступному прикладі, функція має два параметри: `from` і `text`.

```js run
function showMessage(*!*from, text*/!*) { // parameters: from, text
function showMessage(*!*from, text*/!*) { // параметри: from, text
alert(from + ': ' + text);
}

*!*showMessage('Ann', 'Hello!');*/!* // Ann: Hello! (*)
*!*showMessage('Ann', "What's up?");*/!* // Ann: What's up? (**)
*!*showMessage('Анна', 'Привіт!');*/!* // Анна: Привіт! (*)
*!*showMessage('Анна', "Як справи?");*/!* // Анна: Як справи? (**)
```

When the function is called in lines `(*)` and `(**)`, the given values are copied to local variables `from` and `text`. Then the function uses them.
Під час виклику функції з цими параметрами, в рядках `(*)` та `(**)` відбувається копіювання значень параметрів в локальні змінні `from` та `text`. Ці змінні використовує функція.

Here's one more example: we have a variable `from` and pass it to the function. Please note: the function changes `from`, but the change is not seen outside, because a function always gets a copy of the value:
Ось ще один приклад: маємо змінну `from`, яку передаємо в функцію. Зауважте: функція змінює значення `from`, проте ці зміни не видно назовні, тому що функція завжди отримує копію значення:

```js run
function showMessage(from, text) {

*!*
from = '*' + from + '*'; // make "from" look nicer
from = '*' + from + '*'; // прикрашаємо "from"
*/!*

alert( from + ': ' + text );
}

let from = "Ann";
let from = "Анна";

showMessage(from, "Hello"); // *Ann*: Hello
showMessage(from, "Привіт"); // *Анна*: Привіт

// the value of "from" is the same, the function modified a local copy
alert( from ); // Ann
// значення "from" те саме, функція змінила локальну копію
alert( from ); // Анна
```

When a value is passed as a function parameter, it's also called an *argument*.
Коли значення передається як параметр функції, то його ще називають *аргумент*.

In other words, to put these terms straight:
Кажучи "на хлопський розум":

- A parameter is the variable listed inside the parentheses in the function declaration (it's a declaration time term)
- An argument is the value that is passed to the function when it is called (it's a call time term).
- Параметр — це змінна всередині дужок функції (використовується під час оголошення функції)
- Аргумент — це значення, передане в функцію під час її виклику (використовується під час виконання функції).

We declare functions listing their parameters, then call them passing arguments.
Ми оголошуємо функції, вказуючи їхні параметри, потім викликаємо їх, передаючи аргументи.

In the example above, one might say: "the function `sayMessage` is declared with two parameters, then called with two arguments: `from` and `"Hello"`".
Дехто може сказати, що в прикладі вище "функцію `sayMessage` оголошено з двома параметрами, потім викликано з двома аргументами: `from` і `"Привіт"`".


## Default values
Expand All @@ -191,7 +191,7 @@ If a function is called, but an argument is not provided, then the corresponding
For instance, the aforementioned function `showMessage(from, text)` can be called with a single argument:

```js
showMessage("Ann");
showMessage('Ann');
```

That's not an error. Such a call would output `"*Ann*: undefined"`. As the value for `text` isn't passed, it becomes `undefined`.
Expand Down Expand Up @@ -330,13 +330,14 @@ function showMovie(age) {

In the code above, if `checkAge(age)` returns `false`, then `showMovie` won't proceed to the `alert`.

````smart header="A function with an empty `return` or without it returns `undefined`"
If a function does not return a value, it is the same as if it returns `undefined`:
````smart header="A function with an empty `return`or without it returns`undefined`" If a function does not return a value, it is the same as if it returns `undefined`:

```js run
function doNothing() { /* empty */ }
function doNothing() {
/* empty */
}

alert( doNothing() === undefined ); // true
alert(doNothing() === undefined); // true
```

An empty `return` is also the same as `return undefined`:
Expand All @@ -346,9 +347,10 @@ function doNothing() {
return;
}

alert( doNothing() === undefined ); // true
alert(doNothing() === undefined); // true
```
````

`````

````warn header="Never add a newline between `return` and the value"
For a long expression in `return`, it might be tempting to put it on a separate line, like this:
Expand Down Expand Up @@ -376,7 +378,7 @@ return (
)
```
And it will work just as we expect it to.
````
`````

## Naming a function [#function-naming]

Expand Down Expand Up @@ -440,12 +442,11 @@ The first variant uses a label:
```js
function showPrimes(n) {
nextPrime: for (let i = 2; i < n; i++) {

for (let j = 2; j < i; j++) {
if (i % j == 0) continue nextPrime;
}

alert( i ); // a prime
alert(i); // a prime
}
}
```
Expand All @@ -470,7 +471,7 @@ function isPrime(n) {
}
```

The second variant is easier to understand, isn't it? Instead of the code piece we see a name of the action (`isPrime`). Sometimes people refer to such code as *self-describing*.
The second variant is easier to understand, isn't it? Instead of the code piece we see a name of the action (`isPrime`). Sometimes people refer to such code as _self-describing_.

So, functions can be created even if we don't intend to reuse them. They structure the code and make it readable.

Expand Down