Lazy evaluation, also known as non-strict evaluation, call-by-need and deffered execution, is an evaluation strategy that waits until the value is needed to compute the result of a function and is particularly useful for functional programming. It's clear that a line of code that states x = func()
is calling for x
to be assigned to the returned value by func()
. But what x
actually equates to does not matter until it is needed. Waiting to call func()
until x
is needed is known as lazy evaluation.
This strategy can result in a major increase in performance, especially when used with method chains and arrays, the favorite program flow techniques of the functional programmer.
One exciting benefit of lazy evaluation is the existence of infinite series. Because nothing is actually computed until it can't be delayed any further, it's possible to do this:
// wishful JavaScript pseudocode: var infinateNums = range(1 to infinity); var tenPrimes = infinateNums.getPrimeNumbers().first(10);
This opens the door for many possibilities: asynchronous execution, parallelization, and composition, just to name a few.
However, there's one problem: JavaScript does not perform Lazy evaluation on its own. That being said, there exist libraries for JavaScript that simulate lazy evaluation very well. That is the subject of , Setting Up the Functional Programming Environment.