Defining default argument values

An interesting new feature for functions is the possibility of defining default values for missing arguments. We could write a function to calculate nth roots that, by default, would calculate square roots:

// Source file: src/default_arguments.js

function root(a: number, n: number = 2): number {
return a ** (1 / n);
}

// Or, equivalently:
// const root = (a: number, n: number = 2): number => a ** (1 / n);

console.log(root(125, 3)); // 5
console.log(root(4)); // 2
console.log(root(9, undefined)); // 3

As seen in the third example, passing undefined is equivalent to omitting the value. This means that you can provide default values for any parameter: a call such as someFunction(undefined, 22, undefined) would use default values for the first and third arguments, and 22 as the second one.

Default values can also be used for methods and constructors. In the following Counter class, the inc() method, if not provided with a number, will increment the counter by 1. Also, when constructing the counter, if you don't provide an initial value, zero will be used:

// Source file: src/default_arguments.js

class Counter {
count: number; // required by Flow

constructor(i: number = 0) {
this.count = 0;
}

inc(n: number = 1) {
this.count += n;
}
}

const cnt = new Counter();
cnt.inc(3);
cnt.inc();
cnt.inc();

console.log(cnt.count); // 5

As a last detail, you can use values from previous arguments to calculate the default values of later ones. A simple nonsense example shows this; I'll skip type declarations since they are not relevant here:

// Source file: src/default_arguments.js

function nonsense(a = 2, b = a + 1, c = a * b, d = 9) {
console.log(a, b, c, d);
}

nonsense(1, 2, 3, 4); // 1 2 3 4
nonsense(); // 2 3 6 9
nonsense(undefined, 4, undefined, 6); // 2 4 8 6

Using default values is a very practical way to simplify the usage of functions, particularly in the case of complex APIs with many parameters, but allowing sensible values for whatever the user omits.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.196.211