loading...
Cover image for #7DaysJS: Factorial and Average

#7DaysJS: Factorial and Average

lautarolobo profile image Lautaro Lobo Originally published at lautarolobo.xyz on ・1 min read

Welcome to day 1 of 7 Days of JavaScript! A 7 days challenge to crack your head up into some simple but complex algorithms. Today we’ll work on writing two math functions, factorial and average.

To test and run JavaScript, you need the JSC compiler.

Just kidding! A compiler?! You can run it in your own browser!

But, I’ve found this website: Playcode.io. It has all I want, a minimalistic dark theme and a clean console. You can run the code wherever you want, but I encourage you to use Playcode, everything is just nicer.

Enough introduction, let’s dive right in!

Factorial

So the factorial function takes a Natural number n, and returns the product between all the Naturales numbers that are between 1 and n, like this:

5
//1*2*3*4*5
120

Average

The average function is a well known one. It takes an array of numbers, sums them and divides that sum by the length of the initial array. Here’s an example:

[1,5,8,4]
//(1+5+8+4)/4
4.5

Now it’s your turn. Give them a try, especially if you are kinda newbie on JavaScript because you’ll build a good understanding of how loops work.

Did you solve them already? Try a different approach! Making more than one solution will strengthen your knowledge, giving you some flexibility when facing problems. And that’s key when programming.

Here are the solutions.

See ya!

Posted on by:

lautarolobo profile

Lautaro Lobo

@lautarolobo

While you read this I'm learning something new. CS ♥️

Discussion

markdown guide
 

const fact = (n) => n == 1 || n == 0 ? 1 : n * fact(n - 1);

const avg = (arr = []) => arr.length ? arr.reduce((a, b) => a + b) / arr.length : 0;

 

Today I relearned what a factorial is! Thanks!