- Notifications
You must be signed in to change notification settings - Fork179
Functions#127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
tarasyyyk merged 16 commits intojavascript-tutorial:function-basicsfromhypeofpipe:first-steps/function-basicsJul 13, 2021
Uh oh!
There was an error while loading.Please reload this page.
Merged
Functions#127
Changes fromall commits
Commits
Show all changes
16 commits Select commitHold shift + click to select a range
360e678
First part of article.md
hypeofpipe55203a9
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk8a08422
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyykd1b38cb
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk9347c84
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk99a4606
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk7360f68
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk81913d5
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk9476b85
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyykb68b89a
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyke55c3c9
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk6c99a89
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk2ac2bc3
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyykc4e6355
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk8c3f1ae
Update 1-js/02-first-steps/15-function-basics/article.md
tarasyyyk198a5a5
Merge branch 'function-basics' into first-steps/function-basics
tarasyyykFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
115 changes: 58 additions & 57 deletions1-js/02-first-steps/15-function-basics/article.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,40 +1,40 @@ | ||
#Функції | ||
Досить часто нам потрібно виконати подібну дію в багатьох місцях скрипту. | ||
Наприклад, нам треба показати приємне повідомлення, коли користувач входить або виходить з системи і може ще десь. | ||
Функції — це головні "будівельні блоки" програми. Вони дозволяють робити ті самі дії багато разів в коді без повторення. | ||
Ми вже стикались з такими вбудованими функціями, як-от `alert(message)`, `prompt(message, default)`та `confirm(question)`.Але ми теж можемо створювати свої функції. | ||
##Оголошення (декларація) функцій | ||
Щоб створити функцію нам треба її _оголосити_. | ||
Це виглядає ось так: | ||
```js | ||
function showMessage() { | ||
alert('Всім привіт!'); | ||
} | ||
``` | ||
Спочатку ми пишемо`function`— це ключове слово (keyword), яке дає зрозуміти комп’ютеру, що далі буде оголошення функції. Потім — *назву функції*, тоді список її *параметрів* в дужках (розділені комою). Якщо параметрів немає, ми залишаємо _пусті дужки_. І нарешті, код функції, який також називають *тілом функції* між фігурними дужками. | ||
```js | ||
function name(parameter1, parameter2, ... parameterN) { | ||
...тіло функції... | ||
} | ||
``` | ||
Нашу нову функцію можна викликати, написавши її ім’я і дужки: `showMessage()`. | ||
Наприклад: | ||
```js run | ||
function showMessage() { | ||
alert( 'Шановні друзі!' ); | ||
} | ||
*!* | ||
@@ -43,96 +43,96 @@ showMessage(); | ||
*/!* | ||
``` | ||
Виклик`showMessage()`виконує код із тіла функції. В цьому випадку, ми побачимо повідомлення двічі. | ||
Цей приклад яскраво демонструє одну з найголовніших цілей функції - уникнення повторення коду. | ||
Якщо нам потрібно змінити повідомлення, достатньо змінити тіло функції, яке виводить це повідомлення. | ||
##Локальні змінні | ||
Змінна, яка оголошена в функції доступна лише в тілі цієї функції. | ||
До прикладу: | ||
```js run | ||
function showMessage() { | ||
*!* | ||
let message = "Бажаю вам 36.6"; //локальна змінна | ||
*/!* | ||
alert( message ); | ||
} | ||
showMessage(); //Бажаю вам 36.6 | ||
tarasyyyk marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
alert( message ); // <--Помилка! Змінна недоступна поза функцією | ||
``` | ||
##Зовнішні змінні | ||
Функція може використовувати зовнішні змінні, наприклад: | ||
```js run no-beautify | ||
let *!*userName*/!* = 'Іван'; | ||
function showMessage() { | ||
let message = 'Привіт, ' + *!*userName*/!*; | ||
alert(message); | ||
} | ||
showMessage(); //Привіт, Іван | ||
``` | ||
Функція має повний доступ до зовнішньої змінної. Вона теж може її змінювати. | ||
Наприклад: | ||
```js run | ||
let *!*userName*/!* = 'Іван'; | ||
function showMessage() { | ||
tarasyyyk marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
*!*userName*/!* = "Богдан"; // (1)змінено зовнішню змінну | ||
let message = 'Здоровенькі були, ' + *!*userName*/!*; | ||
tarasyyyk marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
alert(message); | ||
} | ||
alert( userName ); // *!*Іван*/!*перед викликом функції showMessage | ||
showMessage(); | ||
alert( userName ); // *!*Богдан*/!*,значення було змінено після виклику функції showMessage | ||
``` | ||
Зовнішня змінна використовується тоді, коли немає локальної. | ||
Якщо всередині функції є змінна з таким самим ім’ям, то вона *затьмарює* зовнішню. Наприклад, наступний код використовує локальну змінну`userName`.Зовнішня ігнорується. | ||
```js run | ||
let userName = 'Іван'; // оголошення зовнішньої змінної | ||
function showMessage() { | ||
*!* | ||
let userName = "Богдан"; //оголошення локальної змінної | ||
*/!* | ||
let message = 'Привіт, ' + userName; // *!*Богдан*/!* | ||
alert(message); | ||
} | ||
//функція завжди віддасть перевагу локальним змінним | ||
showMessage(); | ||
alert( userName ); // *!*Іван*/!*,без змін, функція не змінила глобальну змінну | ||
``` | ||
```smart header="Глобальні змінні" | ||
Змінні, оголошені поза будь-якими функціями (такі як зовнішня зміння`userName`з коду вище), називаються *глобальні* змінні. | ||
Глобальні змінні доступні в будь-якій функції (окрім випадків, коли глобальна змінна затьмарена локальною). | ||
Хорошою практикою вважається мінімізація використання глобальних змінних. У сучасному коді є декалька або одна глобальна змінна. Більшість змінних знаходяться в межах функцій. Іноді, буває корисно зберігати "загальні" дані (на рівні проєкту) в таких глобальних змінних. | ||
``` | ||
## Parameters | ||
@@ -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'); | ||
``` | ||
That's not an error. Such a call would output `"*Ann*: undefined"`. As the value for `text` isn't passed, it becomes `undefined`. | ||
@@ -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`: | ||
```js run | ||
function doNothing() { | ||
/* empty */ | ||
} | ||
alert(doNothing() === undefined); // true | ||
``` | ||
An empty `return` is also the same as `return undefined`: | ||
@@ -346,9 +347,10 @@ function doNothing() { | ||
return; | ||
} | ||
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: | ||
@@ -376,7 +378,7 @@ return ( | ||
) | ||
``` | ||
And it will work just as we expect it to. | ||
````` | ||
## Naming a function [#function-naming] | ||
@@ -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 | ||
} | ||
} | ||
``` | ||
@@ -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_. | ||
So, functions can be created even if we don't intend to reuse them. They structure the code and make it readable. | ||
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.