Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 829 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!

Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.

Delay Evaluation with LazyBox

1:26 JavaScript lesson by

We rewrite the Box example using lazy evaulation

Get the Code Now
click to level up

egghead.io comment guidelines


We rewrite the Box example using lazy evaulation

With Box, we are able to map over each function, and pass our input to output, and work-like function composition here. If we run it, we get a lowercase A here, as it goes through and trims, turns things into numbers, and whatnot.

Now we could also define a lazybox. A lazybox will take, instead of an X, will take a G here for a function. We want to convert our value that's right there, our concrete value, to a function that will eventually return our value.

Sometimes this is referred to as a Church encoding. What we can do here is define a map. How would that work? It takes our F, and we want to return a lazybox that has a function inside. Since this is function composition, we could quite literally just run F of G here, and have our function composition.

Fold works the same way, except fold will not bottle it back up. It'll just run it right away, so we don't need another layer of the lazybox here. What we get from this is that none of this will actually run, if I run my node there. It will just sit here.

In fact, we could go ahead and console.log, there we go, and see that nothing runs. Now if we bring it back, and we run fold, that's like pulling the trigger. There we are. We have the same results.

This gives us purity by virtue of laziness. Basically, nothing happens, so we don't have any impure side effects, until the very end, when we call fold. We're pushing it all the way down to the bottom. This is how a variety of types define map, where they have a function inside them instead of a concrete value, such as promises, observables, or streams, things like this.

Joel's Head
Why are we asking?