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
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,71 @@
└── 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`.

Check notice on line 91 in modules/35-calling-functions/135-calling-functions-default-params/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-calling-functions/135-calling-functions-default-params/es/README.md#L91

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/35-calling-functions/135-calling-functions-default-params/es/README.md:91:163: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

## 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.
Loading
Loading