In some cases, we may allow methods/functions to have optional parameters. We will step through an example of such a case.

Note: Generally we will assume that the passed param count will match the specified (listed) param count (in the given method header). The optional params are for special cases.

Let's say we have this problem:

  • "aRadius" is an optional parameter (if it is not passed, then it will be "undefined")
  • We want to always initialize the ivar "this.radius" to a number (default 0)
constructor(aRadius) {
	this.radius = aRadius;
}
In try 1 we simply assign the param to the ivar.

However, when the param is not passed (i.e. is "undefined") then that means "this.radius" will be set to an "undefined" value.

We need "radius" to a number, so this will not work.
constructor(aRadius) {
	this.radius = aRadius;
}
Heer we use the handy ternary operator to handle the "undefined" case.

If "aRadius" is not equal to undefined, we use it, otherwise we use the default 0.

This works. This added logic "guards" against an "undefined" value.
constructor(aRadius) {
	this.radius = (aRadius !== undefined) ? aRadius : 0;
}