Public
Edited
Jul 15, 2021
2 stars
Insert cell
md`# Named Parameters for Functions.`
Insert cell
md`First, we'll create a function that can allow us to require some parameters for the function and alert us when they are not set.`
Insert cell
function required(name) {
throw new Error(`missing required parameter: ${name}`);
}
Insert cell
md`Second, we'll create a Goblin Object. Each goblin should have a size, a color, and a disposition. In this case, we are making disposition a required parameter.`
Insert cell
function Goblin({size = "small", color = "green", disposition = required("disposition")}={}) {
let goblin = {size:size, color:color, disposition:disposition}
return goblin;
}
Insert cell
md`This Goblin object will not inititate because we did not pass in a disposition.`
Insert cell
goblin = new Goblin({'size':'medium', 'color':'blue'})
Insert cell
md`This other Goblin object will initiate just fine, even though we left out color. It will use the default color set in the constructor function.`
Insert cell
otherGoblin = new Goblin({'size':'large','disposition':'friendly'})
Insert cell
md`Using named parameters helps in several ways:
1. Providing a name along with the parameter’s value
2. Avoiding unnecessary “empty” values to reach the nth position
3. Adding a new parameter doesn’t change the position of others`
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more