Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ sayHello(); // => Hello, World!
```

В задачах, где нужно реализовать функцию, вызывать её самим не нужно — это сделают автоматические тесты. Пример вызова показан лишь для того, чтобы вы понимали, как функция будет использоваться.

> **Примечание:** в файле уже есть строка `export default …` — она служебная, нужна системе проверки; что такое экспорт, разберём в уроке про модули.
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,7 @@ printAverage(6, 4); // => 5

Здесь `a` и `b` — входные параметры, `total` содержит их сумму, `average` получается делением суммы на 2, а `console.log()` выводит результат.

## Стрелочные функции

В JavaScript есть и сокращённая запись через стрелку `=>`:

```javascript
const greet = (name) => {
console.log(`Hello, ${name}!`);
};

greet('Alice'); // => Hello, Alice!
```

Обе формы равнозначны; стрелочную функцию записывают в переменную. Подробнее этот синтаксис мы разберём в отдельном уроке.
В JavaScript есть и другая, сокращённая форма записи функций — стрелочная. Ей посвящён отдельный урок дальше в этом модуле.

## Переиспользование и читаемость

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ To add parameters to your function, simply specify them within parentheses when

```javascript
// str - parameter
const getLastChar = (str) => {
function getLastChar(str) {
// calculate the index of the last character
// extract it, and return it
return str[str.length - 1];
};
}

getLastChar('Hexlet'); // "t"
getLastChar('Goo'); // "o"
Expand All @@ -24,9 +24,9 @@ A specific value can't be a parameter, the point of a parameter is that the valu
A function can have two, three or more parameters. Below is an example of a function that finds the average between two numbers:

```javascript
const average = (x, y) => {
function average(x, y) {
return (x + y) / 2;
};
}

average(1, 5); // 3
average(1, 2); // 1.5
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,18 @@ De la descripción y los ejemplos de código, podemos hacer las siguientes concl
Definición de la función:

```javascript
const getLastChar = (text) => {
function getLastChar(text) {
// Calculamos el índice del último carácter como la longitud de la cadena - 1
return text[text.length - 1];
};
}
```

Analicémoslo. Entre paréntesis se especifica el nombre de la variable `text`, que es nuestro parámetro. El nombre del parámetro puede ser cualquier cosa. Lo importante es que refleje el significado del valor que contiene. Podríamos haber definido la función de esta manera:

```javascript
const getLastChar = (str) => {
function getLastChar(str) {
return str[str.length - 1];
};
}
```

El valor específico del parámetro dependerá de cómo se llame a esta función.
Expand All @@ -66,9 +66,9 @@ De la misma manera, se pueden especificar dos, tres o más parámetros. Cada par

```javascript
// función para encontrar el número medio
const average = (a, b) => {
function average(a, b) {
return (a + b) / 2;
};
}

average(1, 5); // 3
average(1, 2); // 1.5
Expand All @@ -85,9 +85,9 @@ Lo mismo se aplica a los métodos. Pueden requerir cualquier cantidad de paráme
Para crear tales funciones y métodos, debemos especificar la cantidad necesaria de parámetros en la definición, separándolos por comas y dándoles nombres descriptivos. A continuación se muestra un ejemplo de la definición de la función `replace()`, que reemplaza una parte de una cadena por otra:

```javascript
const replace = (text, from, to) => {
function replace(text, from, to) {
// aquí va el cuerpo de la función, pero lo omitimos para no distraernos
};
}

replace('google', 'go', 'mo'); // moogle
```
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const truncate = (text, length) => {
function truncate(text, length) {
// BEGIN
const result = `${text.slice(0, length)}...`;
return result;
// END
};
}

export default truncate;
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,18 @@ getLastChar(name2); // o
Определение функции:

```javascript
const getLastChar = (text) => {
function getLastChar(text) {
// Вычисляем индекс последнего символа как длина строки - 1
return text[text.length - 1];
};
}
```

Разберем его. В скобках указывается имя переменой `text`, которая служит нам параметром. Имя параметра может быть любым. Главное, чтобы оно отражало смысл того значения, которое содержится внутри. Мы могли бы определить функцию и вот так:

```javascript
const getLastChar = (str) => {
function getLastChar(str) {
return str[str.length - 1];
};
}
```

Конкретное значение параметра будет зависеть от вызова этой функции.
Expand All @@ -66,9 +66,9 @@ getLastChar(text); // g

```javascript
// функция по нахождению среднего числа
const average = (a, b) => {
function average(a, b) {
return (a + b) / 2;
};
}

average(1, 5); // 3
average(1, 2); // 1.5
Expand All @@ -85,10 +85,10 @@ average(1, 2); // 1.5
Для создания таких функций и методов, нужно в определении указать нужное количество параметров через запятую, дав им понятные имена. Ниже пример определения функции `replace()`, которая заменяет в слове одну часть строки на другую:

```javascript
const replace = (text, from, to) => {
function replace(text, from, to) {
// здесь тело функции, но мы его
// опускаем, чтобы не отвлекаться
};
}

replace('google', 'go', 'mo'); // moogle
```
Expand Down
Loading