JavaScript: Functions with a variable number of parameters
An interesting feature of some functions is the ability to accept a variable number of parameters. This is not about default values. Take a look at this example:
Math.max(1, 10, 3); // 10The Math.max() function finds the maximum value among the passed parameters. How many parameters do you think it expects as input? If you open the documentation for this function, you will see a strange construct:
Math.max([value1[, value2[, ...]]])
This notation means that this function accepts any number of parameters as input (and can even be called without them). The optionality of the passed parameters is described by the brackets [ ], exactly the same way optional parameters with default values are described. The ability to pass any number of parameters is encoded in this part [, ...].
Math.max(1, -3, 2, 3, 2); // 3Everything specified in square brackets is optional. In this notation Math.max([value1[, value2[, ...]]]) there are several such brackets, and they are nested within each other. Let's break down each of them:
- The first square brackets contain
[value1[, value2[, ...]]], which means you can call the function without parameters, since these square brackets contain everything that is passed into the function. If you remove all the contents of these brackets and the brackets themselves, you are left withMath.max()— a call without parameters. - The second square brackets are nested inside the first and contain
[, value2[, ...]]. They indicate that if we specified the first parameter, then we can optionally specify a second parameter. Without these brackets and their contents, the notation would look likeMath.max([value1]). - The third square brackets are nested inside the second and contain
[, ...]. The ellipsis indicates that there can be any number of parameters. If you remove these brackets and their contents, you get a notation likeMath.max([value1[, value2]]).
The comma is inside the square brackets because if we do not specify a parameter, the comma is not needed. Otherwise, a call with a single parameter would look like this Math.max(value1,).
The Math.min() function works similarly, only it looks for the smallest value:
Math.min(1, 10, 3); // 1
Math.min(1, -3, 2, 3, 2); // -3Instructions
Find the minimum value among the numbers 3, -3, 10, 22, 0 using the Math.min() function and print the result to the screen.
Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('hello world', async () => {
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).toBe('-3');
});Teacher's solution will be available in:
20:00
