Sample Video Frame

27: Applying Functions

You don't have to use anonymous callback functions for data transformation. You can pass in more complex full functions to do the processing you need. You can also chain together calls to map, reduce, filter, and find to perform your transformations. In this code I do the calculation I want at the very end in one sequence of calls. You'll find when you get to Promises that this is a common pattern.

You'll also see I threw in a debug function, which is a handy trick for debugging these chains. All it does is print what it's given and return it.

The Code

let pets = [
  {name: 'Yeller', type: 'Dog', age: 12},
  {name: 'Akumano', type: 'Japanese Bobtail Cat', age: 2},
  {name: 'Meaw Peesard', type: 'Siamese Cat', age: 100},
  {name: 'James', type: 'Gecko', age: 2},

const young_pets = (pet) => {
  return pet.age <= 10;

const age_pets = (pet) => {
  return [, pet.age + 10];

const name_age = (pet) => {
  return `${pet[0]} is ${pet[1]}`;

const debug = (msg) => {
  // why am I doing this here?
  return msg;

let age_young_animals = pets.filter(young_pets)
  .map(debug) // this is why

What You Should See

$ node "code.js" 
[ 'Akumano', 12 ]
[ 'James', 12 ]
Akumano is 12
James is 12

Learn JavaScript Today

Register today for the Early Access course and get the all currently available videos and lessons, plus all future modules for no extra charge.

Still Not Sure? Try the next FREE Lesson!