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..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 @@ -1,23 +1,97 @@ +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). Below are its Syntax, Parameters, and Return value sections, with part of the text omitted. + +```text +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. + ... +``` + +Read the description from top to bottom, step by step. + +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)` | +| --- | --- | --- | +| `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 argument can be omitted | We pass `1`, though we could leave it out | + +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) +'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 | + +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. + +## 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..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 @@ -27,26 +27,71 @@ 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). Abajo están sus secciones Syntax, Parameters y Return value; una parte del texto se ha omitido. ```text -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. + ... ``` -Aquí `digits` es la cantidad de decimales. Los corchetes significan que el parámetro es opcional; si no se indica, por defecto será `0`. +La descripción se lee de arriba abajo, paso a paso. -## Cómo trabajar con funciones nuevas +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. -Cuando te encuentras con una función nueva, resulta cómodo seguir un patrón simple: +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. -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. +| 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 argumento se puede omitir | Pasamos `1`, aunque podríamos no pasarlo | -Este enfoque ayuda a entender rápidamente qué parámetros de la función son obligatorios y cuáles opcionales, y qué resultados devuelve. +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) +'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 | + +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`. + +## 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..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 @@ -27,26 +27,71 @@ 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, Parameters и Return value, часть текста пропущена. ```text -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` — количество знаков после запятой. Квадратные скобки означают, что параметр необязателен; если его не указать, по умолчанию будет `0`. +Описание читают сверху вниз по шагам. -## Как работать с новыми функциями +1. Раздел Syntax перечисляет допустимые вызовы, по одному в строке. Метод можно вызвать без аргументов или с одним аргументом `digits`. +2. Раздел Parameters объясняет каждый параметр по имени из Syntax. Метка Optional означает, что аргумент можно пропустить. Последнее предложение описания говорит, что пропущенный `digits` считается равным `0`. +3. Раздел Return value описывает результат. Словосочетание return value переводится как «возвращаемое значение». Метод возвращает строку (string), поэтому в ответе стоят кавычки. +4. Дальше на странице идут исключения и подробности. На первом чтении их можно пропустить. -Когда вы встречаете новую функцию, удобно действовать по простому паттерну: +Имя `digits` обозначает параметр, и при вызове на его место подставляется конкретное значение, например `(10.25).toFixed(1)`. В таблице сопоставлены части справки и аргументы этого вызова. -1. Открыть документацию (например, MDN) и найти сигнатуру функции. -2. Посмотреть примеры использования. -3. Открыть консоль браузера или Node.js и попробовать вызвать функцию с разными аргументами. +| Часть справки | Что она означает | В вызове `(10.25).toFixed(1)` | +| --- | --- | --- | +| `toFixed` | Имя метода | Вызываем `toFixed()` у числа `10.25` | +| `digits` | Количество знаков после запятой | Передаём `1` | +| Метка Optional у `digits` | Аргумент можно пропустить | Передаём `1`, хотя могли бы не передавать | -Такой подход помогает быстро разобраться, какие у функции обязательные и необязательные параметры и какие результаты она возвращает. +Проверим оба случая в [консоли браузера](https://developer.chrome.com/docs/devtools/console/). Знак `>` обозначает строку ввода, а под вызовом консоль печатает результат. + +```console +> (10.25).toFixed(1) +'10.3' +> (10.25).toFixed() +'10' +``` + +Здесь первый вызов передаёт точность `1` и получает строку `'10.3'`. Второй оставляет `digits` по умолчанию и получает строку `'10'`. Так мы сопоставляем справку, объяснение в документации и результат выполнения. + +## Обозначения в справке + +В справочниках необязательный параметр обозначают по-разному. Обозначения помогают прочитать сигнатуру и при вызове в код не переносятся. + +| Запись в справке | Как её читать | +| --- | --- | +| Две строки `toFixed()` и `toFixed(digits)` | Метод вызывается без аргумента или с аргументом `digits` | +| `toFixed([digits])` | Другой способ обозначить необязательный аргумент. Квадратные скобки не входят в вызов | + +Запись `toFixed([digits])` встречается в сторонних справочниках и статьях. Вызов `(10.25).toFixed(1)` передаёт число `1` без скобок. Ни имя `digits`, ни квадратные скобки в такой вызов не копируются. + +Если браузер переводит страницу, имена функций, параметров и символы в сигнатуре нужно сверять с оригиналом. В коде используются исходные имена из документации. Например, перевод слова `digits` как «цифры» помогает понять описание, а в вызов по-прежнему подставляется само значение `1`. + +## Работа с незнакомой функцией + +Чтение справки начинается с задачи. Например, для вывода цены с одним знаком после запятой в разделе Syntax находим вызов с `digits`, в разделе Parameters проверяем смысл этого параметра, в разделе Return value видим, что результат будет строкой, затем пробуем вызов `(10.25).toFixed(1)`. Если результат соответствует описанию, этот вызов можно использовать в программе. + +У другой функции будут свои параметры и правила. По её сигнатуре мы определяем, какие аргументы передать, по описанию узнаём результат и ограничения, а на небольшом примере проверяем своё понимание.