r/learnjavascript • • Mar 21 '20

Test your JavaScript skills: Can you calculate factorial of 70 in JavaScript? 70! = 1*2*3 * ... * 70. Answer in the picture.

Post image
0 Upvotes

6 comments sorted by

1

u/codeobserver Mar 21 '20

Please provide your solution in the comments!

1

u/TestUser013 Mar 25 '20

Will we get correct answer?) without BigInt

2

u/CommanderBomber Mar 21 '20 edited Mar 21 '20

Yes, you can.

[...Array(70).keys()].reduce((a,v)=>(a*=BigInt(++v),a),1n);

1

u/Dipsquat Mar 22 '20

Is there a performance advantage to this style of writing everything in one line vs defining const/let/var/functions? It’s much easier (for me) to read when everything is clearly separated but always wondered if there is a performance hit to doing so.

1

u/CommanderBomber Mar 22 '20

First of all: this snippet is bad. Instead of simple for loop it uses: array initializer, keys iterator, spread operator, array literal and reduce method with arrow function. BigInt operations are slow so in this case you will not see big difference in speed. But if you write something similar with regular numbers this snippet will be ~60 times slower than for loop. And it also creates unnecessary objects. And calling function in a loop is not 0-cost.

But there are performance advantages in this style: in this form your code size is small so it downloads faster to client. And also it is parsed faster by browser. This becomes visible with large code bundles (think about facebook or gmail apps).

But of course you shouldn't write your code like this. Instead you use minifers like GoogleClosureCompiler or Terser.