Lazy vs Early execution


I'm sure you've heard about closures in JavaScript, a powerful concept when a function "remembers" the variables around it even when that function is executed elsewhere.

I'll show you something new, there are two types of execution Lazy vs Eager in Closures:

In the code below you if I ask you at what line we're executing the code(generating 10 A's),I'm sure you're answer would be at 9, and not line 7 this is called Lazy execution only possible with the help of closures.

Downside to this code is that every time we're calling A(), we're recomputing and repeating the process.

No alt text provided for this image

Now let's take a look at another code,

No alt text provided for this image

Now in the code above execution is happening in line 8 itself because we're doing string operation at line 2 which will happen in execution context of repeater. This is called Early execution.

Although we're computing the string only once but only drawback is if we want to compute the string in execution context of another function we cannot.

Follow Nitish saini for more such articles.

#javascriptdeveloper #closures

To view or add a comment, sign in

Others also viewed

Explore topics