1

i was reading through mdn documentation on promises and got my attention this part

Note: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider the arrow function with no arguments: f = () => expression to create the lazily-evaluated expression, and f() to evaluate.

why particularly arrow function is used when it comes it lazy evaluation, it doesn't provide extra feature such caching maybe. so am i missing something?

for example both of them are working in same way for lazy evaluation

let a = (x) => 2*3;

let b = function(){
   return 2 * 3; 
}

if(someCondition){
  console.log(a());
}

if(otherCondition){
  console.log(b());
}
  • 1
    There are definitely differences between regular functions and `=>` functions, but in this case those don't really matter; the article is just saying that JavaScript, like a lot of other languages, is *not* lazy, so if you want an expression evaluated later your only real choice is to wrap it in a function (of whatever kind you want, though `=>` is a little more terse). – Pointy May 26 '21 at 00:09
  • They say **consider** *the arrow function with no arguments*. I'd attribute that statement to the sentiment that programmers are lazy. And it's easier to just slap a `() => ` in front of an expression to turn it into a function than to explicitly write `function(){ return ... }`. Not to some technical reason; at least not in this case. – Thomas May 26 '21 at 00:20

1 Answers1

3

The recommendation was made under the premise

If you are looking to lazily evaluate an expression
(Emphasis mine)

For putting expressions into a function that evaluates them and returns their result, an arrow function provides the simpler syntax. Any normal function can do the same, but an arrow function is more concise (and also it doesn't change this/arguments/super, should your expression contain them).

This argument is not related to lazy evaluation - for that, anything callable would suffice.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375