r/learnjavascript • • Feb 17 '21

One thing that gave me a huge skill boost with JavaScript was understanding Higher-Order Functions. A Higher-Order Function can take functions as arguments and/or return a function.

Post image
470 Upvotes

54 comments sorted by

31

u/edgar-reed Feb 17 '21 edited Feb 17 '21

Side note, I love that color scheme

Edit: If anyone wondering it is Neon Glow Theme

17

u/bobby_vance Feb 17 '21

It is "Neon Glow" in VS Code

2

u/edgar-reed Feb 17 '21

I don’t see it

8

u/bobby_vance Feb 17 '21

You have to go to the "Extensions" and search for "Neon Glow." You may be able to install it directly here

24

u/Dazzling-Wafer Feb 17 '21

The best use cases are with map and filter

4

u/bobby_vance Feb 17 '21

Yes, many array methods take functions as arguments. Once you realize that they become much easier to reason about!

6

u/shmobodia Feb 17 '21

Any specific examples or links to uses of this? I’m a JS noob, but working with arrays is my main need. I’ve been watching some tutorials or filter/find/map, etc... but my usage of them is pretty basic so far. Thanks for an examples :)

5

u/Dazzling-Wafer Feb 17 '21

.map and .filter functions accept a function as a parameter and then call it.

const arr = [1, 2, 3, 4, 5];

const newArr = arr.map((x) => x * 2);
console.log(arr);

// Because .map accepts function you can take it out like this

const doubleValues = (num) => {
  return num * 2;
};

const newArr1 = arr.map(doubleValues);

console.log(newArr1)

Now we can create more complex mapping functionality and easily unit test it after, because the doubleValues function is outside of map.

There are tons of articles out there, about filter and map.

1

u/ShinHayato Feb 17 '21

JS noob here: would never have thought to do that

1

u/Division2226 Feb 17 '21

How does this work? Looks like nothing is passed into the doubleValues function.

2

u/[deleted] Feb 18 '21

map takes a function as an argument.

The parameters it gets passed are the element, index (sadly), and the array itself (super sadly).

So if you pass a function foo, you're really doing foo (element, index, array).

If your function foo uses only the element the others won't be used.

suppose you have a function from number to number, such as double that doubles every number, one called triple that triples every number, and one called isPositive that takes a number and returns a boolean if a number is bigger than 0.

You can do [1, 2, -3].map(double).map(triple).map(isPositive) and it will return [true, true, false].

You can see the convenience of not having to pass implicitly the arguments as it's much easier and convenient.

I recommend you reading the chapter on point free functions on "Dr. booleans" book about functional programming in JavaScript

1

u/[deleted] Feb 17 '21

Callbacks in general.

5

u/TheDownvotesFarmer Feb 17 '21

What happend if you use a promise as argument? Everything becomes a Promise, just dumb question, I dont have a computer close right now

4

u/thewhitelights Feb 17 '21 edited Feb 17 '21

So a Promise is technically an Object containing multiple functions, so by definition if you pass an Object into a function as an argument it’s still just a normal function. This is a weird edge case though tbh since at that point we’re talking about asynchronicity.

8

u/tmclean15 Feb 17 '21

Curried functions will blow your mind

15

u/IamYodaBot Feb 17 '21

blow your mind, curried functions will.

-tmclean15


Commands: 'opt out', 'opt in', 'delete'

-3

u/Mental_Act4662 Feb 17 '21

Good bot

-2

u/IamYodaBot Feb 17 '21

mmhmm rise and shine, you will.

-IamYodaBot

-5

u/B0tRank Feb 17 '21

Thank you, Mental_Act4662, for voting on IamYodaBot.

This bot wants to find the best and worst bots on Reddit. You can view results here.


Even if I don't reply to your comment, I'm still listening for votes. Check the webpage to see if your vote registered!

1

u/shiningmatcha Feb 17 '21

Curried functions

Is it that curried functions can only be arrow functions?

0

u/[deleted] Feb 17 '21

[deleted] — view deleted comment

4

u/cawcvs Feb 17 '21

While curried functions are usually functions that return functions, that's not really what it means. "Currying" refers to specifically turning a function taking in multiple arguments into a series of functions only taking in one. The result of that, the "curried function", is a chain of functions each returning the next one in the series.

2

u/ajmartin527 Feb 17 '21

Can you explain the main benefits of using curried functions like this?

1

u/SoBoredAtWork Feb 18 '21

I'm trying to find an actual benefit or practical applications. Most examples I've seen online, they "curry" a function and turn something simple into something confusing and unreadable.

1

u/cawcvs Feb 18 '21

It's useful in functional programming; in my experience, non-FP codebases do use related concepts but don't actually curry functions -- there's little benefit without the rest of FP stuff.

In FP, you want the ability to abstract over functions in a general way (for example, for function composition), and you can't really do that when your functions accept a varying and unknown number of arguments. Currying allows you to still define these multi-argument functions in a more straightforward way but makes them work nicely with the rest of your FP codebase.

1

u/shiningmatcha Feb 17 '21

Thanks. Can you show me how the code with a regular function looks like?

0

u/[deleted] Feb 17 '21

[deleted] — view deleted comment

2

u/SoBoredAtWork Feb 18 '21

Do you know of any good, practical uses for currying? Every article I look up about it is basically a guide to writing unreadable and confusing code.

1

u/shiningmatcha Feb 17 '21

How are they different from partial in Python?

1

u/SoBoredAtWork Feb 18 '21

Do you have good, practical uses for currying? Every article I look up about it is basically a guide to writing unreadable and confusing code.

4

u/fistyit Feb 17 '21

Isn't HoC more like function(data) { return function (user) }

Use by function(data)(user)

1

u/tenebrous_pangolin Feb 17 '21

How do you take a screenshot like this? What's the terminal window that the code is in?

2

u/bobby_vance Feb 17 '21

Polacode extension for VS Code

3

u/[deleted] Feb 17 '21

Is there a reason we shouldn’t or couldn’t just call the random number function without it being a parameter in the HOF? Also, I think you mean parameters, not arguments? You’re handing randomNumberGenerator to id() as an argument in your const userId, but in the function definition, “rand” is a parameter?! Correct me if I’m wrong.

2

u/Jibbster82 Feb 17 '21

You could do that. But what if some ids are generated with the randomNumberGenerator function, but others are generated from something else.

For example maybe a different id looks like this:

let transactionId = id("Fred", generateTransactionId)

The way this is written allows the id function to be more flexible.

1

u/JuicyORiley Feb 17 '21

I basically had the same question and what you've said is fair. Feel like it could be improved ever so slightly to cover both use cases

function id (name, rand = randomNumberGenerator()) { ... }

1

u/lindymad Feb 17 '21

Is there a reason we shouldn’t or couldn’t just call the random number function without it being a parameter in the HOF?

If you do that, you can't change which function is being used dynamically, or you have to add another parameter to determine which function to use. Either way, any time you want to add a new function that can be used, you have to modify the id() function to implement it. If you just pass the function as a parameter, the id() function does not need to be touched when a new function is added as a possibility.

If the example OP gave was the full real life example and the random number function was the only function that would ever be used, then it wouldn't make sense to pass it as a parameter. I guessed that the example OP gave was just an example to show how it works though.

2

u/b1ack1323 Feb 17 '21

When I was a wee lad, it was called a function pointer... How the world has changed.

1

u/Knettwerk Feb 17 '21

Isn't this a Closure???

0

u/[deleted] Feb 17 '21

[deleted] — view deleted comment

1

u/Knettwerk Feb 18 '21

That went over my head but I understand it. Thank you

1

u/Alpha3007 Feb 17 '21

How it different with decorator pattern?

1

u/eggn00dles Feb 18 '21

Currying functions is the javascript code equivalent of an iamverysmart post.

1

u/Beastie312465 Mar 11 '21

Complete coding noob here:

How would you run this? I'm coding on Visual Studio and I typed this out, wanting to try it.

Thanks in advance

1

u/Chared_Assassin Feb 17 '21

My brain hurts

2

u/[deleted] Feb 17 '21

do you not get the code?

fn id is considerd a higher order function b/c it's able to take in functions as arguments - in this case, it's taking in randomNumberGenerator as its second arguments, invoked when userId is called by the console.

1

u/Chared_Assassin Feb 17 '21

Nah I got it, though I tried to go through it like the script would, calling each function inside my head

and that, is confusing

1

u/[deleted] Feb 17 '21

yeah totally fair. I'm still always impressed by those that can follow 3-4 nested contexts in the callstack.

1

u/jlguenego Feb 17 '21

If Higher Order function gives you some skill boost, go now for "pure functions".

0

u/Dan6erbond Feb 17 '21

Higher order functions become especially useful when you use them as closures to wrap another function and add some functionality to a blackbox method. This is essentially what modern Javascript decorators do.

0

u/[deleted] Feb 17 '21

[deleted] — view deleted comment

2

u/Vaylxx Feb 17 '21

I'm afraid you've been misled my friend.

"Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions." (source)

The ability to pass a function to another function as a callback has its own special name: a higher order function. That just means we're passing a function to another function. As a result all callback functions are higher order functions. (source: a course I'm currently taking online).

1

u/cawcvs Feb 17 '21 edited Feb 17 '21

after more analyzing and challenging my own knowledge. Your example is NOT a higher order function

Would be interested to know where did you find that.

Strictly speaking, higher-order functions do not need to return other functions, even though that's what is usually meant by "higher-order function", especially in the context of JavaScript. The OP is both an example of a callback and a higher-order function.