The idea of lazy evaluation originated from lambda calculus. Lazy evaluation fundamentally means that an expression won’t be evaluated until some function uses it. The technique allows our systems to boost their processing efficiency, but our memory could be severely overloaded. The problem was solved with the help of garbage collection in programming languages like TypeScript.
As a result, lazy evaluation suddenly rose to fame in functional programming for several reasons. It allows the programmer to access data structure components out of order after initializing them, as long as there are no circular dependencies. It also decreases an algorithm’s time complexity by removing transitory computations.
Programmers learning functional programming often wonder about the best language for the job. Several languages like Elixir, Clojure, Haskell, etc., are used throughout the world for functional programming. However, TypeScript is slowly climbing the ranks due to its powerful type system and type inference.
We will look at a function that takes two numbers as input and returns their sum as the output:
function numsum(a: number, b: number): number {return a + b}console.log(numsum(5,15))
Everything is working as intended, but what if the console.log(numsum(5,15))
was replaced with console.log(numsum(5,8+7))
? The system would have executed the 8+7
before calling the function. However, if we used functional programming and the concept of lazy evaluation, then things would have been the opposite.
If we used lazy evaluation, the sum of 8
and 7
would have been calculated when they were needed rather than at the very moment the compiler read them.
Let’s see how we can do that in TypeScript, in the code below:
function lazynumsum(a: () => number, b: () => number): () => number {return () => a() + b();}console.log(lazynumsum(() => 5, () => 8+7)());
We can see that the output is the same as before, but this time we used the concept of lazy evaluation. We achieved it by wrapping everything up as a function. Therefore, this is a concept used in functional programming.
We can now use the lazy evaluation concept, also known as delayed evaluation, with TypeScript in our programming tasks.
Free Resources