A Quest to Understanding Higher Order Functions

zoekhall

Zoe Hall

Posted on April 26, 2022

A Quest to Understanding Higher Order Functions

When starting your quest to become a programmer, researching different topics online can be daunting. Initially armed with only the basics, sources like MDN Web Docs and Stack Overflow are simultaneously helpful and overwhelming. When faced with an initially puzzling concept, contextual learning can help with comprehension and a deeper understanding of currently unfamiliar topics. Contextual learning is based on what individuals find familiar, but there is something almost everyone will be familiar with (even if they don’t know it) - the hero’s journey.

The hero’s journey or ‘the monomyth’ is what Joseph Campbell posits is the underlying framework for almost every hero-quest driven story. Unless a person has been under a rock and denied media or literature (absolutely no judgment if so), you’ve probably witnessed the hero’s journey within well known tales such as Star Wars, the Hobbit, the Odyssey, Harry Potter, Lilo and Stitch, the Lion King, the Matrix, or any Indiana Jones flick (to name just a few). Using the monomyth as our contextual learning basis - lets explore a different way of learning about higher-order functions through the lens of our own hero's journey!

The Birth of the dragonSlayer

Call to Adventure/Departure

A long time ago, in the land of JavaScript, on a particularly rainy day in July, a visiting prince was captured by a dragon. The resident princess was enraged by the audacity of the dragon and worried the neighboring kingdom would see this as an excuse to go to war if she let their prince get eaten by a dragon. There was no help for it, she vowed she would rescue him herself and immediately began to prepare.

After grabbing the basic necessities it was time to determine what she should use in order to fight the dragon. This being her first impending altercation with a dragon, the princess didn't know what she should expect. She wanted something that would be able to adapt and return different results depending on the situation she found herself in. After a few minutes of careful thought, she had her ‘aha!’ moment. There was only one type of weapon with the flexibility she was looking for. The princess declared she would create the type of weapon JavaScript was known for: the deadly and magical function weapon.

It was custom in JavaScript to simultaneously declare your intent to create a function and name the soon to be crafted weapon. Such a weapon would need a worthy identifier so the bards would be able to sing its name when recounting her brave deeds. Being a pragmatic person, the princess gave the weapon a name specific to its purpose - dragonSlayer.

The function weapon's flexibility came from its being imbued with the ability to process different situational inputs and return countless different results based on those inputs. But the princess didn't want to create a basic function weapon, she was determined to create the fabled Higher Order Function weapon. This was a function known for its ability to add enhanced functionality by either accepting other functions as inputs or even returning other functions. To get started, the princess whipped out her trusty notepad in order to write out her thoughts and determine her strategy.

Image description

Now that she had a basic idea of what she was creating, she gathered the parentheses, curly brackets, semi-colons, and function calls she would need in order to weld her function together. Starting with dragonSlayer, she created the base of the function by hammering her parameters into the parentheses and with the impenetrable curly brackets fashioned next and alongside. Next came the delicate part of the process fashioning within the curly brackets, the function to be returned (henceforth known as the sub-weapon). The sub-weapon first required the same treatment as the initial function (except for forgoing the tradition of function naming). It was then imbued with a conditional statement - that would control the flow of the sword's energy. When successfully invoked, the sword would be defined by a glowing light and perform whatever task/result it was told to complete. Else, the sword would have no definition ie be undefined.

function dragonSlayer(requiredAction, desiredResult){
   return function (actualAction){
      if(requiredAction === actualAction){
         return desiredResult; 
      }
   }
}
Enter fullscreen mode Exit fullscreen mode

The formidable weapon - dragonSlayer

After such intensive and time-consuming labor, it was time to hurriedly create those activation tools that would allow the sword to be invoked. It was common knowledge that all functions had to be paired with a function call in order to be activated. Stamped with its accompanying weapon's name with attached parentheses, function calls are made to intake different inputs (colloquially known as arguments) and communicate these arguments to the weapon to take the place of the parameters. For the purposes of the function weapons, think of them as similar to an audio/video recorder.

But Higher Order Functions required additional function calls to activate the weapons within them. The princess decided to create a variable to hold the first weapon call. This variable would then be used to call the sub-weapon and invoke the final weapon return. Having the choice of a few different variables, the princess decided to use a classic var. She stamped on an identifying name (callToAction) and attached the dragonSlayer function call to it with an assignment operator. Then she grabbed another blank function call and stamped the name of the variable onto it. Voila! dragonSlayer and its activation tools had been made. Not even stopping for a brief respite, she embarked on the next stage of her journey to save the hapless prince!

var callToAction = dragonSlayer();
callToAction(); 
Enter fullscreen mode Exit fullscreen mode

The activation tools: variable and function call

Initiation

After a perilous journey through desert and tundra, she arrived at the dragon's lair. Creeping as close to the lair as she dared, she hid behind a rock and peered above it. She spotted the prince tied up with gold chains atop the dragon's hoard. Unfortunately, the impulsive prince spied her at the same time. Upon seeing her, he yelled 'Help me, Princess Badass! You're my only hope!"

Her opportunity for stealth now non-existent - she had to take immediate action. She told her variable the action she hoped to accomplish and the desired result “do the hokey pokey and turn yourself about”, “stab dragon eye ball”. She then made sure her next functionCall was ready to record her action for the final invocation. The princess rushed forth and started the hokey pokey, but in her haste she failed to turn herself about. She fell on her bum and dragonSlayer lay stagnant in her hand. Mortified and frightened she raced out of the cave. The dragon chortled at this utter failure and didn't bother to follow what was obviously no threat.

function dragonSlayer(requiredAction, desiredResult){
   return function (actualAction){
      if(requiredAction === actualAction){
         return desiredResult; 
      }
   }
}

var callToAction = dragonSlayer(“do the hokey pokey and turn yourself about”, “stab dragon eye ball”);

callToAction("do the hokey pokey"); 
Enter fullscreen mode Exit fullscreen mode

dragonSlayer in action - initial attempt

The princess was almost out of sight of the cave when she thought "Okay, nope - this is not how this is going to go. I didn’t go to all this trouble just to run away." She rushed back to the cave and once again told the variable her intentions ("throw up the middle finger", "point against dragon throat"). And she did exactly that! dragonSlayer glowed and sprang to life, leveling itself against the dragon's throat.

function dragonSlayer(requiredAction, desiredResult){
   return function (actualAction){
      if(requiredAction === actualAction){
         return desiredResult; 
      }
   }
}

var callToAction = dragonSlayer("throw up the middle finger", "point against dragon throat");

callToAction("throw up the middle finger"); 
Enter fullscreen mode Exit fullscreen mode

dragonSlayer in action - successful attempt

The dragon threw up her claws and wings in surrender. "Please don't!" yelled the dragon. "I know it probably wasn't the best way to go about it, but I was sick of you humans robbing me blind. There are a lot of sentimental items in my hoard... I didn’t want to hurt anyone. I just want to be left alone." Listening to the dragon, the princess's rage lessened. She understood the value of sentimentality and, as an introvert, the importance of boundaries and personal space. Sympathizing with the dragon's plight, the princess removed dragonSlayer from the dragon's throat and pledged to do what she could upon her return to rectify the situation as long as the dragon communicated in the future, instead of resorting to kidnapping.

Return

With a newfound respect for the importance of communication, the princess threw the prince over her shoulder and began the long walk home. Upon her return, she issued a decree that the dragon should be left completely alone. The prince and the princess became penpals and they all lived happily ever after.

Image description

💖 💪 🙅 🚩
zoekhall
Zoe Hall

Posted on April 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related