A JavaScript lab
npm install javascript-lab- Create a JavaScript function that loops through a function Array
Since functions in JavaScript are "first-class" objects, it means they can be
treated like any other data type in JavaScript (Number, String, et al.). A
fun way to experience this truth is to load up an Array of Functions and
then call each Function.
Let's create an Array of dog-care functions so that we can report on the
activities we take in caring for Byron the Poodle.
When this program runs, it should print out:
```
console.log("Wake Byron the poodle");
console.log("Leash Byron the poodle");
console.log("Walk to the park with Byron the poodle");
console.log("Throw the frisbee for Byron the poodle");
console.log("Walk home with Byron the poodle");
console.log("Unleash Byron the poodle");
Start by creating a function for every activity that you see listed above:
For example:
`js`
function wakeDog() {
console.log("Wake Byron the poodle");
}
...
But wait, if we write it in this way, all of our uses of this function will be
for Byron the poodle. Let's _generalize_ now and make each function take adogName and dogBreed parameter. Thus:
`jsWake ${dogName} the ${dogBreed}
function wakeDog(dogName, dogBreed) {
console.log();`
}
...
Additionally: Each function should return the string that it creates. That
is, we should create a String, log it to the console (using console.log()), and return that String.
Continue writing _"generalized"_ functions for
* wakeDogleashDog
* walkToPark
* throwFrisbee
* walkHome
* unleashDog
*
Each function's implementation will be a generalized invocation of
console.log().
Next, create our "Array o' Functions!" Create a variable called routine. ThisArray
variable will be an all of the functions we've just defined.
Lastly, create the function called exerciseDog that will take in two
arguments:
* dogNamedogBreed
*
The function's implementation should
* Iterate over the routine ArraydogName
* Call each function in the array and
* pass the and dogBreed received by exerciseDog() to the function as they are _called_Array
* capture the result of each function's call
* return an of all those functions' return values
This lab demonstrates the power of Functions as first-class data. We canArrays
stack them up in or assign them inside of Objects or save them toArray
variables, or iterate over them. Instead of _merely_ having s ofString`s and other familiar items, we can stuff them with _work_. And that's
nothing short of amazing!