From 4d51dc4695dc94a05f3e0b5fff1251c5f78067f0 Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Thu, 5 Nov 2026 15:30:43 +0500 Subject: [PATCH 1/3] =?UTF-8?q?feat(functions):=20=D0=BE=D0=B1=D1=8A=D1=8F?= =?UTF-8?q?=D1=81=D0=BD=D0=B8=D1=82=D1=8C=20=D1=87=D1=82=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D0=B8=20JavaScript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: CONTENT-763 Co-Authored-By: Claude Opus 5.5 --- .../en/README.md | 81 ++++++++++++++++--- .../es/README.md | 58 ++++++++++--- .../ru/README.md | 58 ++++++++++--- 3 files changed, 164 insertions(+), 33 deletions(-) diff --git a/modules/35-calling-functions/135-calling-functions-default-params/en/README.md b/modules/35-calling-functions/135-calling-functions-default-params/en/README.md index 56bba1be..5e9b9b9e 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/en/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/en/README.md @@ -1,23 +1,86 @@ +Some functions have **optional parameters**. This means a default value is set for them in advance, and you can omit such a parameter when calling the function. -Consider the `round()` function, which rounds an integer: +Let's look at the `toFixed()` method, which rounds a number to a given number of decimal places. `toFixed()` is a method, that is, a function attached to a value and called with a dot. We'll cover methods in detail in the lesson about objects. ```javascript -const result = round(10.25, 0); // 10 +const result = (10.25).toFixed(1); // => '10.3' ``` -We pass two parameters to it: the number to round and the precision of rounding. `0` means that it will round to an integer, and the decimal part will simply be discarded. +Note the quotes in the result. `toFixed()` returns a **string**, not a number, so you can't use it directly in further calculations. -In most cases, we need to round exactly to an integer (and not to tenths, for example), so designers of the `round()` function have made the second parameter **optional** and set it to a **default value of `0`**. So, you can choose to not specify the second parameter and the result will be the same: +We passed it one value, the rounding precision (1 decimal place). But this parameter is optional. If you omit it, the default value `0` is used, and the number is rounded to an integer: ```javascript -const result = round(10.25); // 10 +console.log((10.25).toFixed()); // => '10' ``` -We can specify precision by passing another parameter: +If you need a different precision, specify it explicitly: ```javascript -// rounding to one decimal place -const result = round(10.25, 1); // 10.3 +console.log((3.14159).toFixed(2)); // => '3.14' +console.log((3.14159).toFixed(4)); // => '3.1416' ``` -If a JavaScript function accepts optional arguments, they always come after the required ones. Their number varies depending on the function itself, but they always go next to each other and at the end of the list of arguments. +```text +(10.25).toFixed(1) → argument: 1 → '10.3' +(10.25).toFixed() → argument: (0) → '10' + └── default value +``` + +The only parameter of `toFixed()`, `digits`, is optional. Another function may have a different number of parameters and different default values. + +## How to read a function's documentation + +Documentation describes what data a function accepts and what result it returns. The reference for JavaScript's built-in functions lives on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference). A function's page is split into sections. The Syntax section shows the function's name, its parameters, and their order. The Parameters section explains what each parameter is for, and the Return value section describes the result. You need all three sections to write a call. + +Let's look at the [reference for `toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). The Syntax section has two lines. + +```text +toFixed() +toFixed(digits) +``` + +Each line describes a valid call. You can call the method with no arguments or with one argument, `digits`. The name `digits` stands for a parameter, and in a call you put a concrete value in its place, for example `(10.25).toFixed(1)`. + +The table matches the parts of the reference to the arguments of this call. + +| Part of the reference | What it means | In the call `(10.25).toFixed(1)` | +| --- | --- | --- | +| `toFixed` | Method name | We call `toFixed()` on the number `10.25` | +| `digits` | Number of decimal places | We pass `1` | +| The Optional label next to `digits` | The parameter is optional, `0` is used without it | We pass `1` instead of the default value | + +The Optional label sits in the Parameters section next to the parameter name. It tells you the argument can be omitted. The text under the name explains what happens then. For `toFixed()`, a missing `digits` is treated as `0`, so the number is rounded to an integer. + +The Return value section describes the result. The `toFixed()` reference says the method returns a string representing the number in fixed-point notation. The signature shows a valid call, and the description of the result explains why the answer is in quotes. + +Let's check both cases in the interactive Node.js shell (REPL), which starts with the `node` command. The `>` sign is the shell prompt, and after each call the shell prints the result. + +```console +> (10.25).toFixed(1) +'10.3' +> (10.25).toFixed() +'10' +``` + +The first call passes the precision `1` and gets the string `'10.3'`. The second leaves `digits` at its default and gets the string `'10'`. This is how we match the reference, the explanation in the documentation, and the actual result. + +## Notation in references + +References mark optional parameters in different ways. These marks help you read the signature and are not copied into the call. + +| Notation in the reference | How to read it | +| --- | --- | +| Two lines, `toFixed()` and `toFixed(digits)` | The method is called without an argument or with the `digits` argument | +| `toFixed([digits])` | Another way to mark an optional argument. The square brackets are not part of the call | +| `toFixed(fractionDigits?: number): string` | This is how the editor's hint shows the signature. The `?` sign marks an optional parameter, and the types of the parameter and the result follow the colons | + +The `toFixed([digits])` notation appears in older references. The call `(10.25).toFixed(1)` passes the number `1` without brackets. Neither the name `digits` nor the square brackets go into the call. + +If your browser translates the page, check function names, parameter names, and symbols in the signature against the original. Code uses the original names from the documentation. + +## Working with an unfamiliar function + +Reading a reference starts with a task. For example, to show a price with one decimal place, we find the call with `digits` in the Syntax section, check what this parameter means in Parameters, see in Return value that the result is a string, and then try the call `(10.25).toFixed(1)`. If the result matches the description, the call can go into the program. + +Another function will have its own parameters and rules. Its signature tells us which arguments to pass, its description tells us the result and the limits, and a small example lets us check our understanding. diff --git a/modules/35-calling-functions/135-calling-functions-default-params/es/README.md b/modules/35-calling-functions/135-calling-functions-default-params/es/README.md index 926d4e01..25fd2695 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/es/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/es/README.md @@ -27,26 +27,60 @@ console.log((3.14159).toFixed(4)); // => '3.1416' └── valor por defecto ``` -La cantidad de parámetros opcionales depende de cada función, pero los obligatorios van siempre antes de los opcionales. +En `toFixed()` el único parámetro, `digits`, es opcional. Otra función puede tener otra cantidad de parámetros y otros valores por defecto. -## La firma de una función +## Cómo leer la documentación de una función -Cada función tiene una **firma**: la descripción de su nombre, sus parámetros y el orden en que se usan. La firma ayuda a entender qué datos espera la función y qué ocurrirá si los parámetros no se indican. +La documentación describe qué datos recibe una función y qué resultado devuelve. La referencia de las funciones integradas de JavaScript está en [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference). La página de una función se divide en secciones. La sección Syntax muestra el nombre de la función, sus parámetros y su orden; la sección Parameters explica para qué sirve cada parámetro, y la sección Return value describe el resultado. Para escribir una llamada hacen falta las tres secciones. -En la documentación, los parámetros opcionales se muestran a menudo entre corchetes. Por ejemplo, la firma de `toFixed`: +Veamos la [referencia de `toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). En la sección Syntax hay dos líneas. ```text -toFixed([digits]) +toFixed() +toFixed(digits) ``` -Aquí `digits` es la cantidad de decimales. Los corchetes significan que el parámetro es opcional; si no se indica, por defecto será `0`. +Cada línea describe una llamada válida. El método se puede llamar sin argumentos o con un argumento `digits`. El nombre `digits` designa un parámetro, y en la llamada se sustituye por un valor concreto, por ejemplo `(10.25).toFixed(1)`. -## Cómo trabajar con funciones nuevas +La tabla relaciona las partes de la referencia con los argumentos de esa llamada. -Cuando te encuentras con una función nueva, resulta cómodo seguir un patrón simple: +| Parte de la referencia | Qué significa | En la llamada `(10.25).toFixed(1)` | +| --- | --- | --- | +| `toFixed` | Nombre del método | Llamamos a `toFixed()` sobre el número `10.25` | +| `digits` | Cantidad de decimales | Pasamos `1` | +| Etiqueta Optional junto a `digits` | El parámetro es opcional, sin él se usa `0` | Pasamos `1` en lugar del valor por defecto | -1. Abrir la documentación (por ejemplo, MDN) y buscar la firma de la función. -2. Mirar los ejemplos de uso. -3. Abrir la consola del navegador o de Node.js y probar a llamar a la función con distintos argumentos. +La etiqueta Optional aparece en la sección Parameters junto al nombre del parámetro. Indica que el argumento se puede omitir. Qué pasa al omitirlo lo explica el texto bajo el nombre. En `toFixed()`, si falta `digits`, se toma como `0`, es decir, el número se redondea a entero. -Este enfoque ayuda a entender rápidamente qué parámetros de la función son obligatorios y cuáles opcionales, y qué resultados devuelve. +La sección Return value describe el resultado. La expresión inglesa return value significa «valor devuelto». La referencia de `toFixed()` dice que el método devuelve una cadena con el número en notación de punto fijo. La firma muestra una llamada válida, y la descripción del resultado explica por qué la respuesta aparece entre comillas. + +Comprobemos los dos casos en la consola interactiva de Node.js (REPL), que se inicia con el comando `node`. El signo `>` es el indicador de la consola, y después de cada llamada la consola imprime el resultado. + +```console +> (10.25).toFixed(1) +'10.3' +> (10.25).toFixed() +'10' +``` + +La primera llamada pasa la precisión `1` y obtiene la cadena `'10.3'`. La segunda deja `digits` con su valor por defecto y obtiene la cadena `'10'`. Así relacionamos la referencia, la explicación de la documentación y el resultado de la ejecución. + +## Notación en la referencia + +Las referencias marcan los parámetros opcionales de distintas formas. Estas marcas ayudan a leer la firma y no se copian en la llamada. + +| Notación en la referencia | Cómo leerla | +| --- | --- | +| Dos líneas, `toFixed()` y `toFixed(digits)` | El método se llama sin argumento o con el argumento `digits` | +| `toFixed([digits])` | Otra forma de marcar un argumento opcional. Los corchetes no forman parte de la llamada | +| `toFixed(fractionDigits?: number): string` | Así muestra la firma la ayuda del editor. El signo `?` marca un parámetro opcional, y tras los dos puntos aparecen los tipos del parámetro y del resultado | + +La notación `toFixed([digits])` aparece en referencias antiguas. La llamada `(10.25).toFixed(1)` pasa el número `1` sin corchetes. Ni el nombre `digits` ni los corchetes se copian en la llamada. + +Si el navegador traduce la página, hay que comparar los nombres de funciones y parámetros y los símbolos de la firma con el original. En el código se usan los nombres originales de la documentación. Por ejemplo, traducir `digits` como «dígitos» ayuda a entender la descripción, pero en la llamada se sigue poniendo el valor `1`. + +## Trabajar con una función desconocida + +La lectura de la referencia empieza por la tarea. Por ejemplo, para mostrar un precio con un decimal, en la sección Syntax buscamos la llamada con `digits`, en Parameters comprobamos qué significa ese parámetro, en Return value vemos que el resultado será una cadena y después probamos la llamada `(10.25).toFixed(1)`. Si el resultado coincide con la descripción, la llamada se puede usar en el programa. + +Otra función tendrá sus propios parámetros y reglas. Con su firma decidimos qué argumentos pasar, con la descripción conocemos el resultado y las limitaciones, y con un ejemplo pequeño comprobamos lo que hemos entendido. diff --git a/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md b/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md index 54ec8752..21e935ef 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md @@ -27,26 +27,60 @@ console.log((3.14159).toFixed(4)); // => '3.1416' └── значение по умолчанию ``` -Количество необязательных параметров зависит от конкретной функции, но обязательные всегда идут перед необязательными. +У `toFixed()` единственный параметр `digits` необязателен. У другой функции количество параметров и их значения по умолчанию могут отличаться. -## Сигнатура функции +## Как читать документацию функции -У каждой функции есть **сигнатура** — описание её имени, параметров и порядка их использования. Сигнатура помогает понять, какие данные функция ожидает и что произойдёт, если параметры не указаны. +Документация описывает, какие данные принимает функция и какой результат возвращает. Справка о встроенных функциях JavaScript собрана на [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference). Страница функции делится на разделы. Раздел Syntax показывает имя функции, параметры и их порядок, раздел Parameters объясняет назначение каждого параметра, а раздел Return value описывает результат. Чтобы составить вызов, нужны все три раздела. -В документации необязательные параметры часто показывают в квадратных скобках. Например, сигнатура `toFixed`: +Разберём [справку о `toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). В разделе Syntax записаны две строки. ```text -toFixed([digits]) +toFixed() +toFixed(digits) ``` -Здесь `digits` — количество знаков после запятой. Квадратные скобки означают, что параметр необязателен; если его не указать, по умолчанию будет `0`. +Каждая строка описывает допустимый вызов. Метод можно вызвать без аргументов или с одним аргументом `digits`. Имя `digits` обозначает параметр, и при вызове на его место подставляется конкретное значение, например `(10.25).toFixed(1)`. -## Как работать с новыми функциями +В таблице сопоставлены части справки и аргументы этого вызова. -Когда вы встречаете новую функцию, удобно действовать по простому паттерну: +| Часть справки | Что она означает | В вызове `(10.25).toFixed(1)` | +| --- | --- | --- | +| `toFixed` | Имя метода | Вызываем `toFixed()` у числа `10.25` | +| `digits` | Количество знаков после запятой | Передаём `1` | +| Метка Optional у `digits` | Параметр необязателен, без него используется `0` | Передаём `1` вместо значения по умолчанию | -1. Открыть документацию (например, MDN) и найти сигнатуру функции. -2. Посмотреть примеры использования. -3. Открыть консоль браузера или Node.js и попробовать вызвать функцию с разными аргументами. +Метка Optional стоит в разделе Parameters рядом с именем параметра. Из неё видно, что аргумент можно пропустить. Что происходит при пропуске, объясняет текст под именем. У `toFixed()` пропущенный `digits` считается равным `0`, то есть число округляется до целого. -Такой подход помогает быстро разобраться, какие у функции обязательные и необязательные параметры и какие результаты она возвращает. +Раздел Return value описывает результат. Английское словосочетание return value означает «возвращаемое значение». В справке о `toFixed()` сказано, что метод возвращает строку с записью числа в десятичном виде. Сигнатура показывает допустимый вызов, а описание результата объясняет, почему в ответе стоят кавычки. + +Проверим оба случая в интерактивной оболочке Node.js (REPL). Она запускается командой `node`. Знак `>` обозначает приглашение оболочки, а после вызова оболочка печатает результат. + +```console +> (10.25).toFixed(1) +'10.3' +> (10.25).toFixed() +'10' +``` + +Здесь первый вызов передаёт точность `1` и получает строку `'10.3'`. Второй оставляет `digits` по умолчанию и получает строку `'10'`. Так мы сопоставляем справку, объяснение в документации и результат выполнения. + +## Обозначения в справке + +В справочниках необязательный параметр обозначают по-разному. Обозначения помогают прочитать сигнатуру и при вызове в код не переносятся. + +| Запись в справке | Как её читать | +| --- | --- | +| Две строки `toFixed()` и `toFixed(digits)` | Метод вызывается без аргумента или с аргументом `digits` | +| `toFixed([digits])` | Другой способ обозначить необязательный аргумент. Квадратные скобки не входят в вызов | +| `toFixed(fractionDigits?: number): string` | Так сигнатуру показывает подсказка редактора. Знак `?` отмечает необязательный параметр, после двоеточий указаны типы параметра и результата | + +Запись `toFixed([digits])` встречается в старых справочниках. Вызов `(10.25).toFixed(1)` передаёт число `1` без скобок. Ни имя `digits`, ни квадратные скобки в такой вызов не копируются. + +Если браузер переводит страницу, имена функций, параметров и символы в сигнатуре нужно сверять с оригиналом. В коде используются исходные имена из документации. Например, перевод слова `digits` как «цифры» помогает понять описание, а в вызов по-прежнему подставляется само значение `1`. + +## Работа с незнакомой функцией + +Чтение справки начинается с задачи. Например, для вывода цены с одним знаком после запятой в разделе Syntax находим вызов с `digits`, в разделе Parameters проверяем смысл этого параметра, в разделе Return value видим, что результат будет строкой, затем пробуем вызов `(10.25).toFixed(1)`. Если результат соответствует описанию, этот вызов можно использовать в программе. + +У другой функции будут свои параметры и правила. По её сигнатуре мы определяем, какие аргументы передать, по описанию узнаём результат и ограничения, а на небольшом примере проверяем своё понимание. From b5927bb6aded0c047765c4f4cfd29c3b34ace42a Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Thu, 5 Nov 2026 16:02:37 +0500 Subject: [PATCH 2/3] =?UTF-8?q?fix(functions):=20=D0=BF=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B5=D1=80=D1=8F=D1=82=D1=8C=20=D0=B2=D1=8B=D0=B7=D0=BE=D0=B2?= =?UTF-8?q?=D1=8B=20=D0=B2=20=D0=BA=D0=BE=D0=BD=D1=81=D0=BE=D0=BB=D0=B8=20?= =?UTF-8?q?=D0=B1=D1=80=D0=B0=D1=83=D0=B7=D0=B5=D1=80=D0=B0=20=D0=B8=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B7=D0=BE=D0=B1=D1=80=D0=B0=D1=82=D1=8C=20padSta?= =?UTF-8?q?rt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: CONTENT-763 Co-Authored-By: Claude Opus 5.5 --- .../135-calling-functions-default-params/en/README.md | 7 +++---- .../135-calling-functions-default-params/es/README.md | 7 +++---- .../135-calling-functions-default-params/ru/README.md | 7 +++---- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/modules/35-calling-functions/135-calling-functions-default-params/en/README.md b/modules/35-calling-functions/135-calling-functions-default-params/en/README.md index 5e9b9b9e..c91395c7 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/en/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/en/README.md @@ -48,13 +48,13 @@ The table matches the parts of the reference to the arguments of this call. | --- | --- | --- | | `toFixed` | Method name | We call `toFixed()` on the number `10.25` | | `digits` | Number of decimal places | We pass `1` | -| The Optional label next to `digits` | The parameter is optional, `0` is used without it | We pass `1` instead of the default value | +| The Optional label next to `digits` | The argument can be omitted | We pass `1`, though we could leave it out | The Optional label sits in the Parameters section next to the parameter name. It tells you the argument can be omitted. The text under the name explains what happens then. For `toFixed()`, a missing `digits` is treated as `0`, so the number is rounded to an integer. The Return value section describes the result. The `toFixed()` reference says the method returns a string representing the number in fixed-point notation. The signature shows a valid call, and the description of the result explains why the answer is in quotes. -Let's check both cases in the interactive Node.js shell (REPL), which starts with the `node` command. The `>` sign is the shell prompt, and after each call the shell prints the result. +Let's check both cases in the [browser console](https://developer.chrome.com/docs/devtools/console/). The `>` sign marks the input line, and the console prints the result under each call. ```console > (10.25).toFixed(1) @@ -73,9 +73,8 @@ References mark optional parameters in different ways. These marks help you read | --- | --- | | Two lines, `toFixed()` and `toFixed(digits)` | The method is called without an argument or with the `digits` argument | | `toFixed([digits])` | Another way to mark an optional argument. The square brackets are not part of the call | -| `toFixed(fractionDigits?: number): string` | This is how the editor's hint shows the signature. The `?` sign marks an optional parameter, and the types of the parameter and the result follow the colons | -The `toFixed([digits])` notation appears in older references. The call `(10.25).toFixed(1)` passes the number `1` without brackets. Neither the name `digits` nor the square brackets go into the call. +The `toFixed([digits])` notation appears in third-party references and articles. The call `(10.25).toFixed(1)` passes the number `1` without brackets. Neither the name `digits` nor the square brackets go into the call. If your browser translates the page, check function names, parameter names, and symbols in the signature against the original. Code uses the original names from the documentation. diff --git a/modules/35-calling-functions/135-calling-functions-default-params/es/README.md b/modules/35-calling-functions/135-calling-functions-default-params/es/README.md index 25fd2695..d8923ae5 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/es/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/es/README.md @@ -48,13 +48,13 @@ La tabla relaciona las partes de la referencia con los argumentos de esa llamada | --- | --- | --- | | `toFixed` | Nombre del método | Llamamos a `toFixed()` sobre el número `10.25` | | `digits` | Cantidad de decimales | Pasamos `1` | -| Etiqueta Optional junto a `digits` | El parámetro es opcional, sin él se usa `0` | Pasamos `1` en lugar del valor por defecto | +| Etiqueta Optional junto a `digits` | El argumento se puede omitir | Pasamos `1`, aunque podríamos no pasarlo | La etiqueta Optional aparece en la sección Parameters junto al nombre del parámetro. Indica que el argumento se puede omitir. Qué pasa al omitirlo lo explica el texto bajo el nombre. En `toFixed()`, si falta `digits`, se toma como `0`, es decir, el número se redondea a entero. La sección Return value describe el resultado. La expresión inglesa return value significa «valor devuelto». La referencia de `toFixed()` dice que el método devuelve una cadena con el número en notación de punto fijo. La firma muestra una llamada válida, y la descripción del resultado explica por qué la respuesta aparece entre comillas. -Comprobemos los dos casos en la consola interactiva de Node.js (REPL), que se inicia con el comando `node`. El signo `>` es el indicador de la consola, y después de cada llamada la consola imprime el resultado. +Comprobemos los dos casos en la [consola del navegador](https://developer.chrome.com/docs/devtools/console/). El signo `>` marca la línea de entrada, y debajo de cada llamada la consola imprime el resultado. ```console > (10.25).toFixed(1) @@ -73,9 +73,8 @@ Las referencias marcan los parámetros opcionales de distintas formas. Estas mar | --- | --- | | Dos líneas, `toFixed()` y `toFixed(digits)` | El método se llama sin argumento o con el argumento `digits` | | `toFixed([digits])` | Otra forma de marcar un argumento opcional. Los corchetes no forman parte de la llamada | -| `toFixed(fractionDigits?: number): string` | Así muestra la firma la ayuda del editor. El signo `?` marca un parámetro opcional, y tras los dos puntos aparecen los tipos del parámetro y del resultado | -La notación `toFixed([digits])` aparece en referencias antiguas. La llamada `(10.25).toFixed(1)` pasa el número `1` sin corchetes. Ni el nombre `digits` ni los corchetes se copian en la llamada. +La notación `toFixed([digits])` aparece en referencias y artículos de terceros. La llamada `(10.25).toFixed(1)` pasa el número `1` sin corchetes. Ni el nombre `digits` ni los corchetes se copian en la llamada. Si el navegador traduce la página, hay que comparar los nombres de funciones y parámetros y los símbolos de la firma con el original. En el código se usan los nombres originales de la documentación. Por ejemplo, traducir `digits` como «dígitos» ayuda a entender la descripción, pero en la llamada se sigue poniendo el valor `1`. diff --git a/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md b/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md index 21e935ef..ad526e01 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md @@ -48,13 +48,13 @@ toFixed(digits) | --- | --- | --- | | `toFixed` | Имя метода | Вызываем `toFixed()` у числа `10.25` | | `digits` | Количество знаков после запятой | Передаём `1` | -| Метка Optional у `digits` | Параметр необязателен, без него используется `0` | Передаём `1` вместо значения по умолчанию | +| Метка Optional у `digits` | Аргумент можно пропустить | Передаём `1`, хотя могли бы не передавать | Метка Optional стоит в разделе Parameters рядом с именем параметра. Из неё видно, что аргумент можно пропустить. Что происходит при пропуске, объясняет текст под именем. У `toFixed()` пропущенный `digits` считается равным `0`, то есть число округляется до целого. Раздел Return value описывает результат. Английское словосочетание return value означает «возвращаемое значение». В справке о `toFixed()` сказано, что метод возвращает строку с записью числа в десятичном виде. Сигнатура показывает допустимый вызов, а описание результата объясняет, почему в ответе стоят кавычки. -Проверим оба случая в интерактивной оболочке Node.js (REPL). Она запускается командой `node`. Знак `>` обозначает приглашение оболочки, а после вызова оболочка печатает результат. +Проверим оба случая в [консоли браузера](https://developer.chrome.com/docs/devtools/console/). Знак `>` обозначает строку ввода, а под вызовом консоль печатает результат. ```console > (10.25).toFixed(1) @@ -73,9 +73,8 @@ toFixed(digits) | --- | --- | | Две строки `toFixed()` и `toFixed(digits)` | Метод вызывается без аргумента или с аргументом `digits` | | `toFixed([digits])` | Другой способ обозначить необязательный аргумент. Квадратные скобки не входят в вызов | -| `toFixed(fractionDigits?: number): string` | Так сигнатуру показывает подсказка редактора. Знак `?` отмечает необязательный параметр, после двоеточий указаны типы параметра и результата | -Запись `toFixed([digits])` встречается в старых справочниках. Вызов `(10.25).toFixed(1)` передаёт число `1` без скобок. Ни имя `digits`, ни квадратные скобки в такой вызов не копируются. +Запись `toFixed([digits])` встречается в сторонних справочниках и статьях. Вызов `(10.25).toFixed(1)` передаёт число `1` без скобок. Ни имя `digits`, ни квадратные скобки в такой вызов не копируются. Если браузер переводит страницу, имена функций, параметров и символы в сигнатуре нужно сверять с оригиналом. В коде используются исходные имена из документации. Например, перевод слова `digits` как «цифры» помогает понять описание, а в вызов по-прежнему подставляется само значение `1`. From 797409e386a3d5c32dfcc061eafc74e9a0b447bd Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Thu, 5 Nov 2026 21:20:56 +0500 Subject: [PATCH 3/3] =?UTF-8?q?docs(functions):=20=D0=BF=D0=BE=D0=BA=D0=B0?= =?UTF-8?q?=D0=B7=D0=B0=D1=82=D1=8C=20=D1=84=D1=80=D0=B0=D0=B3=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=20=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20toF?= =?UTF-8?q?ixed()=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D1=81=D0=BA=D0=B0=D0=B7=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: CONTENT-763 Co-Authored-By: Claude Opus 5.5 --- .../en/README.md | 30 +++++++++++++------ .../es/README.md | 30 +++++++++++++------ .../ru/README.md | 30 +++++++++++++------ 3 files changed, 63 insertions(+), 27 deletions(-) diff --git a/modules/35-calling-functions/135-calling-functions-default-params/en/README.md b/modules/35-calling-functions/135-calling-functions-default-params/en/README.md index c91395c7..ff0dc525 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/en/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/en/README.md @@ -33,16 +33,32 @@ The only parameter of `toFixed()`, `digits`, is optional. Another function may h Documentation describes what data a function accepts and what result it returns. The reference for JavaScript's built-in functions lives on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference). A function's page is split into sections. The Syntax section shows the function's name, its parameters, and their order. The Parameters section explains what each parameter is for, and the Return value section describes the result. You need all three sections to write a call. -Let's look at the [reference for `toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). The Syntax section has two lines. +Let's look at the [reference for `toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). Below are its Syntax, Parameters, and Return value sections, with part of the text omitted. ```text -toFixed() -toFixed(digits) +Syntax + toFixed() + toFixed(digits) + +Parameters + digits Optional + The number of digits to appear after the decimal point; should be + a value between 0 and 100, inclusive. If this argument is omitted, + it is treated as 0. + +Return value + A string representing the given number using fixed-point notation. + ... ``` -Each line describes a valid call. You can call the method with no arguments or with one argument, `digits`. The name `digits` stands for a parameter, and in a call you put a concrete value in its place, for example `(10.25).toFixed(1)`. +Read the description from top to bottom, step by step. -The table matches the parts of the reference to the arguments of this call. +1. The Syntax section lists the valid calls, one per line. You can call the method with no arguments or with one argument, `digits`. +2. The Parameters section explains each parameter by the name used in Syntax. The Optional label means the argument can be omitted. The last sentence of the description says that a missing `digits` is treated as `0`. +3. The Return value section describes the result. The method returns a string, which is why the answer is in quotes. +4. Further down, the page covers exceptions and other details. You can skip them on a first read. + +The name `digits` stands for a parameter, and in a call you put a concrete value in its place, for example `(10.25).toFixed(1)`. The table matches the parts of the reference to the arguments of this call. | Part of the reference | What it means | In the call `(10.25).toFixed(1)` | | --- | --- | --- | @@ -50,10 +66,6 @@ The table matches the parts of the reference to the arguments of this call. | `digits` | Number of decimal places | We pass `1` | | The Optional label next to `digits` | The argument can be omitted | We pass `1`, though we could leave it out | -The Optional label sits in the Parameters section next to the parameter name. It tells you the argument can be omitted. The text under the name explains what happens then. For `toFixed()`, a missing `digits` is treated as `0`, so the number is rounded to an integer. - -The Return value section describes the result. The `toFixed()` reference says the method returns a string representing the number in fixed-point notation. The signature shows a valid call, and the description of the result explains why the answer is in quotes. - Let's check both cases in the [browser console](https://developer.chrome.com/docs/devtools/console/). The `>` sign marks the input line, and the console prints the result under each call. ```console diff --git a/modules/35-calling-functions/135-calling-functions-default-params/es/README.md b/modules/35-calling-functions/135-calling-functions-default-params/es/README.md index d8923ae5..4efd53a0 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/es/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/es/README.md @@ -33,16 +33,32 @@ En `toFixed()` el único parámetro, `digits`, es opcional. Otra función puede La documentación describe qué datos recibe una función y qué resultado devuelve. La referencia de las funciones integradas de JavaScript está en [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference). La página de una función se divide en secciones. La sección Syntax muestra el nombre de la función, sus parámetros y su orden; la sección Parameters explica para qué sirve cada parámetro, y la sección Return value describe el resultado. Para escribir una llamada hacen falta las tres secciones. -Veamos la [referencia de `toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). En la sección Syntax hay dos líneas. +Veamos la [referencia de `toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). Abajo están sus secciones Syntax, Parameters y Return value; una parte del texto se ha omitido. ```text -toFixed() -toFixed(digits) +Syntax + toFixed() + toFixed(digits) + +Parameters + digits Optional + The number of digits to appear after the decimal point; should be + a value between 0 and 100, inclusive. If this argument is omitted, + it is treated as 0. + +Return value + A string representing the given number using fixed-point notation. + ... ``` -Cada línea describe una llamada válida. El método se puede llamar sin argumentos o con un argumento `digits`. El nombre `digits` designa un parámetro, y en la llamada se sustituye por un valor concreto, por ejemplo `(10.25).toFixed(1)`. +La descripción se lee de arriba abajo, paso a paso. -La tabla relaciona las partes de la referencia con los argumentos de esa llamada. +1. La sección Syntax enumera las llamadas válidas, una por línea. El método se puede llamar sin argumentos o con un argumento `digits`. +2. La sección Parameters explica cada parámetro por el nombre que aparece en Syntax. La etiqueta Optional indica que el argumento se puede omitir. La última frase de la descripción dice que, si falta `digits`, se toma como `0`. +3. La sección Return value describe el resultado. La expresión inglesa return value significa «valor devuelto». El método devuelve una cadena (string), por eso la respuesta aparece entre comillas. +4. Más abajo la página trata las excepciones y otros detalles. En una primera lectura se pueden saltar. + +El nombre `digits` designa un parámetro, y en la llamada se sustituye por un valor concreto, por ejemplo `(10.25).toFixed(1)`. La tabla relaciona las partes de la referencia con los argumentos de esa llamada. | Parte de la referencia | Qué significa | En la llamada `(10.25).toFixed(1)` | | --- | --- | --- | @@ -50,10 +66,6 @@ La tabla relaciona las partes de la referencia con los argumentos de esa llamada | `digits` | Cantidad de decimales | Pasamos `1` | | Etiqueta Optional junto a `digits` | El argumento se puede omitir | Pasamos `1`, aunque podríamos no pasarlo | -La etiqueta Optional aparece en la sección Parameters junto al nombre del parámetro. Indica que el argumento se puede omitir. Qué pasa al omitirlo lo explica el texto bajo el nombre. En `toFixed()`, si falta `digits`, se toma como `0`, es decir, el número se redondea a entero. - -La sección Return value describe el resultado. La expresión inglesa return value significa «valor devuelto». La referencia de `toFixed()` dice que el método devuelve una cadena con el número en notación de punto fijo. La firma muestra una llamada válida, y la descripción del resultado explica por qué la respuesta aparece entre comillas. - Comprobemos los dos casos en la [consola del navegador](https://developer.chrome.com/docs/devtools/console/). El signo `>` marca la línea de entrada, y debajo de cada llamada la consola imprime el resultado. ```console diff --git a/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md b/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md index ad526e01..d8f92ef2 100644 --- a/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md +++ b/modules/35-calling-functions/135-calling-functions-default-params/ru/README.md @@ -33,16 +33,32 @@ console.log((3.14159).toFixed(4)); // => '3.1416' Документация описывает, какие данные принимает функция и какой результат возвращает. Справка о встроенных функциях JavaScript собрана на [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference). Страница функции делится на разделы. Раздел Syntax показывает имя функции, параметры и их порядок, раздел Parameters объясняет назначение каждого параметра, а раздел Return value описывает результат. Чтобы составить вызов, нужны все три раздела. -Разберём [справку о `toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). В разделе Syntax записаны две строки. +Разберём [справку о `toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). Ниже приведены её разделы Syntax, Parameters и Return value, часть текста пропущена. ```text -toFixed() -toFixed(digits) +Syntax + toFixed() + toFixed(digits) + +Parameters + digits Optional + The number of digits to appear after the decimal point; should be + a value between 0 and 100, inclusive. If this argument is omitted, + it is treated as 0. + +Return value + A string representing the given number using fixed-point notation. + ... ``` -Каждая строка описывает допустимый вызов. Метод можно вызвать без аргументов или с одним аргументом `digits`. Имя `digits` обозначает параметр, и при вызове на его место подставляется конкретное значение, например `(10.25).toFixed(1)`. +Описание читают сверху вниз по шагам. -В таблице сопоставлены части справки и аргументы этого вызова. +1. Раздел Syntax перечисляет допустимые вызовы, по одному в строке. Метод можно вызвать без аргументов или с одним аргументом `digits`. +2. Раздел Parameters объясняет каждый параметр по имени из Syntax. Метка Optional означает, что аргумент можно пропустить. Последнее предложение описания говорит, что пропущенный `digits` считается равным `0`. +3. Раздел Return value описывает результат. Словосочетание return value переводится как «возвращаемое значение». Метод возвращает строку (string), поэтому в ответе стоят кавычки. +4. Дальше на странице идут исключения и подробности. На первом чтении их можно пропустить. + +Имя `digits` обозначает параметр, и при вызове на его место подставляется конкретное значение, например `(10.25).toFixed(1)`. В таблице сопоставлены части справки и аргументы этого вызова. | Часть справки | Что она означает | В вызове `(10.25).toFixed(1)` | | --- | --- | --- | @@ -50,10 +66,6 @@ toFixed(digits) | `digits` | Количество знаков после запятой | Передаём `1` | | Метка Optional у `digits` | Аргумент можно пропустить | Передаём `1`, хотя могли бы не передавать | -Метка Optional стоит в разделе Parameters рядом с именем параметра. Из неё видно, что аргумент можно пропустить. Что происходит при пропуске, объясняет текст под именем. У `toFixed()` пропущенный `digits` считается равным `0`, то есть число округляется до целого. - -Раздел Return value описывает результат. Английское словосочетание return value означает «возвращаемое значение». В справке о `toFixed()` сказано, что метод возвращает строку с записью числа в десятичном виде. Сигнатура показывает допустимый вызов, а описание результата объясняет, почему в ответе стоят кавычки. - Проверим оба случая в [консоли браузера](https://developer.chrome.com/docs/devtools/console/). Знак `>` обозначает строку ввода, а под вызовом консоль печатает результат. ```console