From 235511c6646110b5ee59847e3c25f11795c297f3 Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Tue, 3 Nov 2026 22:14:40 +0500 Subject: [PATCH] =?UTF-8?q?fix(define-functions):=20=D0=B2=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=D0=B8=D1=82=D1=8C=20=D1=81=D1=82=D1=80=D0=B5=D0=BB=D0=BE?= =?UTF-8?q?=D1=87=D0=BD=D1=83=D1=8E=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8?= =?UTF-8?q?=D1=8E=20=D0=BE=D1=81=D0=BD=D0=BE=D0=B2=D0=BD=D0=BE=D0=B9=20?= =?UTF-8?q?=D1=84=D0=BE=D1=80=D0=BC=D0=BE=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit С 2019 года модуль учил стрелочной функции, перенос теории из Python в июне 2026 поставил первой объявление function. Урок определения функции снова вводит стрелочную форму, а объявление и функциональное выражение показывает как записи из чужого кода. Уроки возврата, параметров по умолчанию и аннотаций типов и решения упражнений переведены на стрелочные функции. Co-Authored-By: Claude Opus 5.5 --- .../100-define-function/es/README.md | 56 ++++++++----------- .../100-define-function/index.js | 4 +- .../100-define-function/ru/README.md | 56 ++++++++----------- .../150-return/es/README.md | 24 ++++---- .../40-define-functions/150-return/index.js | 4 +- .../150-return/ru/README.md | 24 ++++---- .../340-default-parameters/es/README.md | 22 ++++---- .../340-default-parameters/index.js | 4 +- .../340-default-parameters/ru/README.md | 22 ++++---- .../350-type-annotations/en/README.md | 4 +- .../350-type-annotations/es/README.md | 16 +++--- .../350-type-annotations/index.js | 4 +- .../350-type-annotations/ru/README.md | 16 +++--- modules/45-logic/10-bool-type/index.js | 4 +- modules/48-conditionals/30-if/index.js | 4 +- modules/48-conditionals/50-else-if/index.js | 4 +- 16 files changed, 126 insertions(+), 142 deletions(-) diff --git a/modules/40-define-functions/100-define-function/es/README.md b/modules/40-define-functions/100-define-function/es/README.md index 72f06c50..d85e55da 100644 --- a/modules/40-define-functions/100-define-function/es/README.md +++ b/modules/40-define-functions/100-define-function/es/README.md @@ -13,9 +13,9 @@ console.log("Hello, JavaScript!"); Para no repetir la misma plantilla, se la puede envolver en una función propia que reciba un parámetro e imprima la cadena necesaria: ```javascript -function sayHello(name) { +const sayHello = (name) => { console.log(`Hello, ${name}!`); -} +}; ``` Ahora se la puede llamar con distintos argumentos: @@ -31,27 +31,27 @@ Parece que el código no se ha reducido, pero apareció otra ventaja: si la func ## La sintaxis de la definición ```javascript -function nombreDeLaFuncion(parámetros) { +const nombreDeLaFuncion = (parámetros) => { cuerpo; -} +}; ``` ```text -function greet(name) { ← palabra clave, nombre y parámetro - return 'Hello, ' + name; ← cuerpo de la función -} +const greet = (name) => { ← nombre, parámetro y flecha + return 'Hello, ' + name; ← cuerpo de la función +}; ``` -La definición empieza con la palabra clave `function`, después va el nombre de la función (con las mismas reglas que las variables), entre paréntesis la lista de parámetros separados por comas, y el cuerpo de la función se encierra entre llaves `{}`. +La definición tiene dos partes. A la derecha del signo `=` está la propia función. Entre paréntesis va la lista de parámetros separados por comas, después la flecha `=>`, y el cuerpo de la función se encierra entre llaves `{}`. A la izquierda está el nombre, y la función se guarda en una constante con las mismas reglas que cualquier otro valor. Por eso al final de la definición va un punto y coma, igual que después de una asignación normal. ## Definir una función no significa llamarla Definir una función no ejecuta su código. El cuerpo se ejecutará solo al llamarla. Mira el ejemplo: ```javascript -function sayHi() { +const sayHi = () => { console.log("Hi!"); -} +}; console.log("El programa continúa…"); ``` @@ -59,9 +59,9 @@ console.log("El programa continúa…"); Aquí la función `sayHi()` está definida, pero su cuerpo no se ejecuta: en la pantalla aparecerá solo `El programa continúa…`. Para que `sayHi()` funcione, hay que llamarla de forma explícita: ```javascript -function sayHi() { +const sayHi = () => { console.log("Hi!"); -} +}; sayHi(); // => Hi! console.log("El programa continúa…"); @@ -72,11 +72,11 @@ console.log("El programa continúa…"); Implementemos una función que **calcula e imprime la media aritmética** de dos números. La media aritmética es la suma de los números dividida por su cantidad. Por ejemplo, la media de 6 y 4: `(6 + 4) / 2 = 5`. ```javascript -function printAverage(a, b) { +const printAverage = (a, b) => { const total = a + b; const average = total / 2; console.log(average); -} +}; printAverage(6, 4); // => 5 ``` @@ -88,9 +88,9 @@ Aquí `a` y `b` son los parámetros de entrada, `total` contiene su suma, `avera El nombre de un parámetro puede ser cualquiera; lo importante es que refleje el sentido del valor que llegará dentro. Con el código de fuera no está relacionado de ninguna manera: ```javascript -function getLastChar(str) { +const getLastChar = (str) => { return str[str.length - 1]; -} +}; // Dentro de la función str será igual a 'Winter is coming'. // El nombre de la variable de fuera no está ligado al nombre del parámetro @@ -110,29 +110,21 @@ console.log("google".replace("mo", "go")); // => google ## Otras formas de escribir funciones -Una función no solo se puede declarar con `function`: también se puede escribir como un valor y asignarla a una constante: +En la documentación y en el código de otras personas la función se define a menudo con la palabra clave `function`: -```javascript -const sayHello = function (name) { - console.log(`Hello, ${name}!`); -}; - -sayHello("Hexlet"); // => Hello, Hexlet! -``` - -Esa forma se llama expresión de función. Fíjate en el punto y coma del final: aquí tenemos una asignación normal a una constante, no una declaración de función. - -La expresión de función tiene una forma corta, la de flecha. En ella la palabra `function` se sustituye por la flecha `=>`, que se coloca después de la lista de parámetros: + -```javascript -const sayHello = (name) => { +```text +function sayHello(name) { console.log(`Hello, ${name}!`); -}; +} sayHello("Hexlet"); // => Hello, Hexlet! ``` -Para nuestras tareas las tres formas son equivalentes: la función se define y luego se llama por su nombre. La forma de flecha es la que más aparece en JavaScript, por eso más adelante en el curso los ejemplos están escritos así. Una lección aparte de este módulo mostrará cómo acortarla todavía más. +Esa forma se llama declaración de función. También aparece la expresión de función `const sayHello = function (name) { … };`, que está construida como la función de flecha, solo que en lugar de la flecha lleva la palabra `function`. + +Para nuestras tareas las tres formas son equivalentes, porque la función se define y luego se llama por su nombre. La forma de flecha es la que más aparece en JavaScript, por eso en el curso los ejemplos están escritos así. Una lección aparte de este módulo mostrará cómo acortarla todavía más. ## Reutilización y legibilidad diff --git a/modules/40-define-functions/100-define-function/index.js b/modules/40-define-functions/100-define-function/index.js index bada2a6d..096f2cb9 100644 --- a/modules/40-define-functions/100-define-function/index.js +++ b/modules/40-define-functions/100-define-function/index.js @@ -1,7 +1,7 @@ // BEGIN -function sayHello() { +const sayHello = () => { console.log("Hello, World!"); -} +}; // END export default sayHello; diff --git a/modules/40-define-functions/100-define-function/ru/README.md b/modules/40-define-functions/100-define-function/ru/README.md index 99104266..d512954f 100644 --- a/modules/40-define-functions/100-define-function/ru/README.md +++ b/modules/40-define-functions/100-define-function/ru/README.md @@ -13,9 +13,9 @@ console.log("Hello, JavaScript!"); Чтобы не повторять один и тот же шаблон, его можно оформить в виде своей функции, которая принимает параметр и печатает нужную строку: ```javascript -function sayHello(name) { +const sayHello = (name) => { console.log(`Hello, ${name}!`); -} +}; ``` Теперь её можно вызывать с разными аргументами: @@ -31,27 +31,27 @@ sayHello("JavaScript"); // => Hello, JavaScript! ## Синтаксис определения ```javascript -function имяФункции(параметры) { +const имяФункции = (параметры) => { тело; -} +}; ``` ```text -function greet(name) { ← ключевое слово, имя и параметр - return 'Hello, ' + name; ← тело функции -} +const greet = (name) => { ← имя, параметр и стрелка + return 'Hello, ' + name; ← тело функции +}; ``` -Определение начинается с ключевого слова `function`, затем идёт имя функции (по тем же правилам, что и у переменных), в скобках — список параметров через запятую, а тело функции заключается в фигурные скобки `{}`. +Определение состоит из двух частей. Справа от знака `=` записана сама функция. В скобках идёт список параметров через запятую, после него стрелка `=>`, а тело функции заключается в фигурные скобки `{}`. Слева стоит имя, и функция сохраняется в константу по тем же правилам, что и любое другое значение. Поэтому в конце определения ставится точка с запятой, как после обычного присваивания. ## Определить функцию — не значит вызвать её Определение функции не запускает её код. Тело выполнится только при вызове. Посмотрите на пример: ```javascript -function sayHi() { +const sayHi = () => { console.log("Hi!"); -} +}; console.log("Программа продолжается…"); ``` @@ -59,9 +59,9 @@ console.log("Программа продолжается…"); Здесь функция `sayHi()` определена, но её тело не выполняется — на экран попадёт только `Программа продолжается…`. Чтобы `sayHi()` сработала, её нужно явно вызвать: ```javascript -function sayHi() { +const sayHi = () => { console.log("Hi!"); -} +}; sayHi(); // => Hi! console.log("Программа продолжается…"); @@ -72,11 +72,11 @@ console.log("Программа продолжается…"); Реализуем функцию, которая **вычисляет и печатает среднее арифметическое** двух чисел. Среднее арифметическое — это сумма чисел, делённая на их количество. Например, среднее от 6 и 4: `(6 + 4) / 2 = 5`. ```javascript -function printAverage(a, b) { +const printAverage = (a, b) => { const total = a + b; const average = total / 2; console.log(average); -} +}; printAverage(6, 4); // => 5 ``` @@ -88,9 +88,9 @@ printAverage(6, 4); // => 5 Имя параметра может быть любым — главное, чтобы оно отражало смысл значения, которое попадёт внутрь. С внешним кодом оно никак не связано: ```javascript -function getLastChar(str) { +const getLastChar = (str) => { return str[str.length - 1]; -} +}; // Внутри функции str будет равна 'Winter is coming'. // Имя переменной снаружи не связано с именем параметра @@ -110,29 +110,21 @@ console.log("google".replace("mo", "go")); // => google ## Другие формы записи -Функцию можно не только объявить через `function`, но и записать как значение и присвоить константе: +В документации и в чужом коде функцию часто определяют через ключевое слово `function`: -```javascript -const sayHello = function (name) { - console.log(`Hello, ${name}!`); -}; - -sayHello("Hexlet"); // => Hello, Hexlet! -``` - -Такую запись называют функциональным выражением. Обратите внимание на точку с запятой в конце: перед нами обычное присваивание константы, а не объявление функции. - -У функционального выражения есть короткая форма, стрелочная. Слово `function` в ней заменяется на стрелку `=>`, которая ставится после списка параметров: + -```javascript -const sayHello = (name) => { +```text +function sayHello(name) { console.log(`Hello, ${name}!`); -}; +} sayHello("Hexlet"); // => Hello, Hexlet! ``` -Для наших задач все три записи равнозначны: функцию определяют, а потом вызывают по имени. Стрелочная форма в JavaScript встречается чаще остальных, поэтому дальше в курсе примеры записаны именно так. Отдельный урок этого модуля покажет, как сократить её ещё сильнее. +Такую запись называют объявлением функции. Встречается и функциональное выражение `const sayHello = function (name) { … };`, которое устроено как стрелочная функция, только вместо стрелки в нём стоит слово `function`. + +Для наших задач все три записи равнозначны, потому что функцию определяют, а потом вызывают по имени. Стрелочная форма в JavaScript встречается чаще остальных, поэтому в курсе примеры записаны именно так. Отдельный урок этого модуля покажет, как сократить её ещё сильнее. ## Переиспользование и читаемость diff --git a/modules/40-define-functions/150-return/es/README.md b/modules/40-define-functions/150-return/es/README.md index d2f4a5b5..d3696f53 100644 --- a/modules/40-define-functions/150-return/es/README.md +++ b/modules/40-define-functions/150-return/es/README.md @@ -7,9 +7,9 @@ Para que una función entregue un resultado se usa la palabra clave especial `re Aquí tienes una función que pone el texto en mayúsculas: ```javascript -function shout(name) { +const shout = (name) => { return name.toUpperCase(); -} +}; const result = shout("hexlet"); console.log(result); // => HEXLET @@ -26,14 +26,14 @@ A diferencia de `console.log()`, `return` no imprime nada. Simplemente devuelve ```javascript // Esta función imprime, pero no devuelve nada -function printSum(a, b) { +const printSum = (a, b) => { console.log(a + b); -} +}; // Esta función devuelve el resultado -function getSum(a, b) { +const getSum = (a, b) => { return a + b; -} +}; // El resultado devuelto se puede usar después const sum = getSum(3, 4); @@ -45,9 +45,9 @@ console.log(sum * 2); // => 14 En `return` normalmente se indica una **expresión**, que primero se evalúa y después se pasa el resultado hacia fuera: ```javascript -function fullName(first, last) { +const fullName = (first, last) => { return `${first} ${last}`; -} +}; const name = fullName("Aria", "Stark"); console.log(name); // => Aria Stark @@ -60,11 +60,11 @@ Primero se evalúa la plantilla de cadena, y ya el valor listo se devuelve hacia A veces en el cuerpo de la función hay que dar varios pasos antes de obtener el resultado. Entonces se escriben varias líneas, y al final se usa `return`. Por ejemplo, una función que formatea un nombre: quita los espacios de los extremos y pasa las letras a mayúsculas. ```javascript -function formatName(name) { +const formatName = (name) => { const clean = name.trim(); const uppercased = clean.toUpperCase(); return uppercased; -} +}; console.log(formatName(" hexlet ")); // => HEXLET ``` @@ -74,10 +74,10 @@ console.log(formatName(" hexlet ")); // => HEXLET Cuando la ejecución llega a `return`, la función termina de inmediato. Todo lo que esté escrito después, dentro de la función, **no se ejecutará**: ```javascript -function example() { +const example = () => { return "listo"; console.log("este código nunca se ejecutará"); -} +}; console.log(example()); // => listo ``` diff --git a/modules/40-define-functions/150-return/index.js b/modules/40-define-functions/150-return/index.js index 4e1b85fd..3e711022 100644 --- a/modules/40-define-functions/150-return/index.js +++ b/modules/40-define-functions/150-return/index.js @@ -1,8 +1,8 @@ -function truncate(text, length) { +const truncate = (text, length) => { // BEGIN const result = `${text.slice(0, length)}...`; return result; // END -} +}; export default truncate; diff --git a/modules/40-define-functions/150-return/ru/README.md b/modules/40-define-functions/150-return/ru/README.md index 1907454e..a2a85bcd 100644 --- a/modules/40-define-functions/150-return/ru/README.md +++ b/modules/40-define-functions/150-return/ru/README.md @@ -7,9 +7,9 @@ Вот функция, которая делает текст заглавным: ```javascript -function shout(name) { +const shout = (name) => { return name.toUpperCase(); -} +}; const result = shout("hexlet"); console.log(result); // => HEXLET @@ -26,14 +26,14 @@ console.log(result2); // => CODE-BASICS ```javascript // Эта функция выводит, но ничего не возвращает -function printSum(a, b) { +const printSum = (a, b) => { console.log(a + b); -} +}; // Эта функция возвращает результат -function getSum(a, b) { +const getSum = (a, b) => { return a + b; -} +}; // Возвращённый результат можно использовать дальше const sum = getSum(3, 4); @@ -45,9 +45,9 @@ console.log(sum * 2); // => 14 В `return` обычно указывают **выражение**, которое сначала вычисляется, а потом результат передаётся наружу: ```javascript -function fullName(first, last) { +const fullName = (first, last) => { return `${first} ${last}`; -} +}; const name = fullName("Aria", "Stark"); console.log(name); // => Aria Stark @@ -60,11 +60,11 @@ console.log(name); // => Aria Stark Иногда в теле функции нужно сделать несколько шагов, прежде чем получить результат. Тогда пишут несколько строк, а в конце используют `return`. Например, функция форматирует имя: убирает пробелы по краям и переводит буквы в верхний регистр. ```javascript -function formatName(name) { +const formatName = (name) => { const clean = name.trim(); const uppercased = clean.toUpperCase(); return uppercased; -} +}; console.log(formatName(" hexlet ")); // => HEXLET ``` @@ -74,10 +74,10 @@ console.log(formatName(" hexlet ")); // => HEXLET Когда выполнение доходит до `return`, функция немедленно завершается. Всё, что написано после него внутри функции, **не выполнится**: ```javascript -function example() { +const example = () => { return "готово"; console.log("этот код никогда не выполнится"); -} +}; console.log(example()); // => готово ``` diff --git a/modules/40-define-functions/340-default-parameters/es/README.md b/modules/40-define-functions/340-default-parameters/es/README.md index 3dfd188f..4572fb00 100644 --- a/modules/40-define-functions/340-default-parameters/es/README.md +++ b/modules/40-define-functions/340-default-parameters/es/README.md @@ -3,9 +3,9 @@ Las funciones pueden recibir parámetros. A veces resulta cómodo fijar un valor Si el argumento no se pasa, se usa ese valor. Si el argumento se indica, reemplaza al valor por defecto. ```javascript -function greet(name = "World") { +const greet = (name = "World") => { console.log(`Hello, ${name}!`); -} +}; greet("Alice"); // => Hello, Alice! greet(); // => Hello, World! (se usó el valor por defecto) @@ -16,16 +16,16 @@ greet(); // => Hello, World! (se usó el valor por defecto) Hagamos una función que repita una cadena varias veces. Que por defecto sea una vez, pero que se pueda indicar otra cantidad si se quiere. Para repetir una cadena, JavaScript tiene el método `repeat()`: ```javascript -function repeat(text, times = 1) { +const repeat = (text, times = 1) => { return text.repeat(times); -} +}; console.log(repeat("Hi")); // => Hi console.log(repeat("Hi", 3)); // => HiHiHi ``` ```text -function repeat(text, times = 1) ← times tiene un valor por defecto +const repeat = (text, times = 1) => ← times tiene un valor por defecto repeat('go') → times = 1 (por defecto) repeat('go', 5) → times = 5 (indicado de forma explícita) @@ -38,9 +38,9 @@ Los parámetros opcionales se indican siempre **al final** de la lista. Por eso Por defecto las palabras se unen con un espacio, pero se puede indicar otro carácter: ```javascript -function joinWords(word1, word2, separator = " ") { +const joinWords = (word1, word2, separator = " ") => { return word1 + separator + word2; -} +}; console.log(joinWords("King", "Road")); // => King Road console.log(joinWords("Dragon", "stone", "-")); // => Dragon-stone @@ -51,9 +51,9 @@ console.log(joinWords("Dragon", "stone", "-")); // => Dragon-stone Una función puede tener más de un parámetro con valor por defecto. Hagamos una función que construya una línea separadora. Por defecto el carácter es el guion y la longitud es 10: ```javascript -function makeLine(symbol = "-", length = 10) { +const makeLine = (symbol = "-", length = 10) => { return symbol.repeat(length); -} +}; console.log(makeLine()); // => ---------- console.log(makeLine("*")); // => ********** @@ -64,9 +64,9 @@ console.log(makeLine("#", 3)); // => ### ## Ejemplo: ocultar el número de una tarjeta ```javascript -function getHiddenCard(cardNumber, starsCount = 4) { +const getHiddenCard = (cardNumber, starsCount = 4) => { return "*".repeat(starsCount) + cardNumber.slice(-4); -} +}; console.log(getHiddenCard("1234567890123456")); // => ****3456 console.log(getHiddenCard("1234567890123456", 2)); // => **3456 diff --git a/modules/40-define-functions/340-default-parameters/index.js b/modules/40-define-functions/340-default-parameters/index.js index 0779a1ee..1d2966ca 100644 --- a/modules/40-define-functions/340-default-parameters/index.js +++ b/modules/40-define-functions/340-default-parameters/index.js @@ -1,7 +1,7 @@ // BEGIN -function getHiddenCard(cardNumber, starsCount = 4) { +const getHiddenCard = (cardNumber, starsCount = 4) => { return "*".repeat(starsCount) + cardNumber.slice(-4); -} +}; // END export default getHiddenCard; diff --git a/modules/40-define-functions/340-default-parameters/ru/README.md b/modules/40-define-functions/340-default-parameters/ru/README.md index 8a758b51..92791b5c 100644 --- a/modules/40-define-functions/340-default-parameters/ru/README.md +++ b/modules/40-define-functions/340-default-parameters/ru/README.md @@ -3,9 +3,9 @@ Если аргумент не передан, используется это значение. Если аргумент указан, он заменяет умолчание. ```javascript -function greet(name = "World") { +const greet = (name = "World") => { console.log(`Hello, ${name}!`); -} +}; greet("Alice"); // => Hello, Alice! greet(); // => Hello, World! (использовано значение по умолчанию) @@ -16,16 +16,16 @@ greet(); // => Hello, World! (использовано значение по у Сделаем функцию, которая повторяет строку несколько раз. По умолчанию пусть будет один раз, но при желании можно указать другое количество. Для повторения строки в JavaScript есть метод `repeat()`: ```javascript -function repeat(text, times = 1) { +const repeat = (text, times = 1) => { return text.repeat(times); -} +}; console.log(repeat("Hi")); // => Hi console.log(repeat("Hi", 3)); // => HiHiHi ``` ```text -function repeat(text, times = 1) ← times имеет значение по умолчанию +const repeat = (text, times = 1) => ← times имеет значение по умолчанию repeat('go') → times = 1 (по умолчанию) repeat('go', 5) → times = 5 (явно указано) @@ -38,9 +38,9 @@ repeat('go', 5) → times = 5 (явно указано) По умолчанию слова соединяются пробелом, но можно указать другой символ: ```javascript -function joinWords(word1, word2, separator = " ") { +const joinWords = (word1, word2, separator = " ") => { return word1 + separator + word2; -} +}; console.log(joinWords("King", "Road")); // => King Road console.log(joinWords("Dragon", "stone", "-")); // => Dragon-stone @@ -51,9 +51,9 @@ console.log(joinWords("Dragon", "stone", "-")); // => Dragon-stone Функция может содержать более одного параметра со значением по умолчанию. Сделаем функцию, которая строит строку-разделитель. По умолчанию символ — дефис, а длина равна 10: ```javascript -function makeLine(symbol = "-", length = 10) { +const makeLine = (symbol = "-", length = 10) => { return symbol.repeat(length); -} +}; console.log(makeLine()); // => ---------- console.log(makeLine("*")); // => ********** @@ -64,9 +64,9 @@ console.log(makeLine("#", 3)); // => ### ## Пример: скрытие номера карты ```javascript -function getHiddenCard(cardNumber, starsCount = 4) { +const getHiddenCard = (cardNumber, starsCount = 4) => { return "*".repeat(starsCount) + cardNumber.slice(-4); -} +}; console.log(getHiddenCard("1234567890123456")); // => ****3456 console.log(getHiddenCard("1234567890123456", 2)); // => **3456 diff --git a/modules/40-define-functions/350-type-annotations/en/README.md b/modules/40-define-functions/350-type-annotations/en/README.md index a5012e7a..d64bbea8 100644 --- a/modules/40-define-functions/350-type-annotations/en/README.md +++ b/modules/40-define-functions/350-type-annotations/en/README.md @@ -11,9 +11,9 @@ A JSDoc comment starts with `/**` and goes right before the function definition. * @param {number} b * @returns {number} */ -function add(a, b) { +const add = (a, b) => { return a + b; -} +}; console.log(add(2, 3)); // => 5 ``` diff --git a/modules/40-define-functions/350-type-annotations/es/README.md b/modules/40-define-functions/350-type-annotations/es/README.md index 027fcc9d..1cc746a2 100644 --- a/modules/40-define-functions/350-type-annotations/es/README.md +++ b/modules/40-define-functions/350-type-annotations/es/README.md @@ -17,9 +17,9 @@ Veámoslo con el ejemplo de una función que calcula la suma de dos valores reci * @param {number} b * @returns {number} */ -function add(a, b) { +const add = (a, b) => { return a + b; -} +}; console.log(add(2, 3)); // => 5 ``` @@ -53,9 +53,9 @@ En esta etapa basta con conocer las anotaciones de los tipos de datos simples, l * @param {number} height * @returns {string} */ -function describe(name, age, height) { +const describe = (name, age, height) => { return `${name}, ${age} años, altura ${height}`; -} +}; console.log(describe("Anna", 25, 1.7)); // => Anna, 25 años, altura 1.7 @@ -68,9 +68,9 @@ Si la función no devuelve nada, como tipo devuelto se indica `void`. Por ejempl * @param {string} name * @returns {void} */ -function printGreeting(name) { +const printGreeting = (name) => { console.log(`Hello, ${name}!`); -} +}; printGreeting("Anna"); // => Hello, Anna! @@ -86,9 +86,9 @@ Las anotaciones funcionan igual tanto para los parámetros obligatorios como par * @param {string} [greeting='Hello'] * @returns {string} */ -function greet(name, greeting = "Hello") { +const greet = (name, greeting = "Hello") => { return `${greeting}, ${name}`; -} +}; console.log(greet("Anna")); // => Hello, Anna console.log(greet("Kirill", "Hi")); // => Hi, Kirill diff --git a/modules/40-define-functions/350-type-annotations/index.js b/modules/40-define-functions/350-type-annotations/index.js index a85e808d..8d34f715 100644 --- a/modules/40-define-functions/350-type-annotations/index.js +++ b/modules/40-define-functions/350-type-annotations/index.js @@ -4,9 +4,9 @@ * @param {number} repetitions * @returns {string} */ -function wordMultiply(text, repetitions) { +const wordMultiply = (text, repetitions) => { return text.repeat(repetitions); -} +}; // END export default wordMultiply; diff --git a/modules/40-define-functions/350-type-annotations/ru/README.md b/modules/40-define-functions/350-type-annotations/ru/README.md index 11db262e..1d23a669 100644 --- a/modules/40-define-functions/350-type-annotations/ru/README.md +++ b/modules/40-define-functions/350-type-annotations/ru/README.md @@ -17,9 +17,9 @@ JSDoc-комментарий начинается с `/**` и располага * @param {number} b * @returns {number} */ -function add(a, b) { +const add = (a, b) => { return a + b; -} +}; console.log(add(2, 3)); // => 5 ``` @@ -53,9 +53,9 @@ add("2", 3); // Argument of type 'string' is not assignable to parameter of type * @param {number} height * @returns {string} */ -function describe(name, age, height) { +const describe = (name, age, height) => { return `${name}, ${age} лет, рост ${height}`; -} +}; console.log(describe("Anna", 25, 1.7)); // => Anna, 25 лет, рост 1.7 @@ -68,9 +68,9 @@ console.log(describe("Anna", 25, 1.7)); * @param {string} name * @returns {void} */ -function printGreeting(name) { +const printGreeting = (name) => { console.log(`Hello, ${name}!`); -} +}; printGreeting("Anna"); // => Hello, Anna! @@ -86,9 +86,9 @@ printGreeting("Anna"); * @param {string} [greeting='Hello'] * @returns {string} */ -function greet(name, greeting = "Hello") { +const greet = (name, greeting = "Hello") => { return `${greeting}, ${name}`; -} +}; console.log(greet("Anna")); // => Hello, Anna console.log(greet("Kirill", "Hi")); // => Hi, Kirill diff --git a/modules/45-logic/10-bool-type/index.js b/modules/45-logic/10-bool-type/index.js index 805a26ac..ac81e315 100644 --- a/modules/45-logic/10-bool-type/index.js +++ b/modules/45-logic/10-bool-type/index.js @@ -1,7 +1,7 @@ // BEGIN -function isPensioner(age) { +const isPensioner = (age) => { return age >= 60; -} +}; // END export default isPensioner; diff --git a/modules/48-conditionals/30-if/index.js b/modules/48-conditionals/30-if/index.js index df0a0378..521285f5 100644 --- a/modules/48-conditionals/30-if/index.js +++ b/modules/48-conditionals/30-if/index.js @@ -1,10 +1,10 @@ // BEGIN -function guessNumber(guess) { +const guessNumber = (guess) => { if (guess === 42) { return "You win!"; } return "Try again!"; -} +}; // END export default guessNumber; diff --git a/modules/48-conditionals/50-else-if/index.js b/modules/48-conditionals/50-else-if/index.js index ba233d0a..243442f9 100644 --- a/modules/48-conditionals/50-else-if/index.js +++ b/modules/48-conditionals/50-else-if/index.js @@ -1,5 +1,5 @@ // BEGIN -function getTrafficLightAction(color) { +const getTrafficLightAction = (color) => { if (color === "green") { return "go"; } else if (color === "yellow") { @@ -9,7 +9,7 @@ function getTrafficLightAction(color) { } return "unknown"; -} +}; // END export default getTrafficLightAction;