In programming, many functions and methods have parameters that are rarely changed. In such cases, these parameters are given default values that can be changed as needed. This slightly reduces the amount of identical code.
For example:
// The function of a raising to a power
// The second parameter has a default value of 2
const pow = (x, base = 2) => {
return x ** base;
};
// three to the second power (two is set by default)
pow(3); // 9
// three to the third power
pow(3, 3); // 27
The default value looks like a regular assignment in the definition. It only works if the parameter is not passed. This takes some practice to get used to it. The default value can exist even if there is only one parameter:
const print = (text = 'nothing') => console.log(text);
print(); // "nothing"
print("Hexlet"); // "Hexlet"
There can be any number of parameters with default values:
const f = (a = 5, b = 10, c = 100) => { ... }
The default values have one limitation. They must go to the very end of the parameter list.
From the syntax point of view, it is impossible to create a function that will have a mandatory parameter next to an optional one:
// This code will be executed with an error
const f = (a = 5, b = 10, c = 100, x) => { ... }
// And this one
const f = (a = 5, x, b = 10, c = 100) => { ... }
// But this one will work
const f = (x, a = 5, b = 10, c = 100) => { ... }
// As well as this one
const f = (x, y, a = 5, b = 10, c = 100) => { ... }