Housoul
Housoul

Reputation: 99

Javascript Higher Order Function:

I am learning HOF at the moment:

weaponsWithNoises = [
  { name: "Phaser", noise: "bssszzsssss", universe: "Star Trek" },
  { name: "Blaster", noise: "Pew Pew", universe: "Star Wars" },
  { name: "Sonic Screwdriver", noise: "Pew Pew", universe: "Dr. Who" },
  { name: "Lightsaber", noise: "Pew Pew", universe: "Star Wars" },
  { name: "Noisy Cricket", noise: "Pew Pew", universe: "Men in Black" },
];


function weaponsFromUniverse(universe) {
  const useableWeapons = weaponsWithNoises.filter(
    (w) => w.universe == universe
  );
  const useWeapon = (weaponName) => {
    const weapon = useableWeapons.find((w) => weaponName == w.name);
    if (weapon) {
      console.log(`used ${weapon.name}: ${weapon.noise}`);
    } else {
      console.log(`${weaponName} is not a part of the ${universe} universe`);
    }
  };

  return useWeapon;
}

// USAGE
const useStarWarsWeapon = weaponsFromUniverse("Star Wars");

useStarWarsWeapon("Blaster"); // console logs 'used Blaster: Pew Pew'
useStarWarsWeapon("Noisy Cricket"); // console logs 'Noisy Cricket is not a part of the Star Wars universe'

In this example, I am really confused, for the usage section:

const useStarWarsWeapon = weaponsFromUniverse("Star Wars");

At this line, "Star Wars" is passed to weaponsFromUniverse, then this function is assigned to useStarWarsWeapon, then "Blaster" is passed to useStarWarsWeapon:

useStarWarsWeapon("Blaster");

Why "Blaster" can be naturally passed to useWeapon in the weaponsFromUniverse?

Upvotes: 0

Views: 43

Answers (1)

fjplaurr
fjplaurr

Reputation: 1950

weaponsFromUniverse returns useWeapon which is a function that receives one parameter called weaponName.

When doing:

 const useStarWarsWeapon = weaponsFromUniverse("Star Wars");

Then useStarWarsWeapon is a function that receives one parameter called weaponName.

Therefore, you can call that function with whatever parameter you want. For example, with Blaster by doing this:

useStarWarsWeapon("Blaster");

Upvotes: 1

Related Questions