Hi guys!

Recently i’m trying to learn a program language called Javascript and i discovered that javascript is a MUST for a front end developer, so here i am trying to conquer javascript.
Okay then i think i’m gonna share something called Factorial and i’m pretty sure we all know what a factorial is. If you need me to refresh your memory then i’ll be glad to explain how it works. Take a look at the explanation below :

5! Means 5 x 4 x 3 x 2 x 1 = 120
4! Means 4 x 3 x 2 x 1 = 36
3! Means 3 x 2 x 1 = 6
2! Means 2 x 1 = 2
1! Means useless… Heheee

Alright then, you get the point so let’s get into the programming.

function factorial (val) {
    If (val == 0 || val == 1) {
      return 1;
    } else {
      return val * factorial (val – 1);

document.write(“8! Is “, factorial (8));

First of all we want to give the logic first and from the explanation (how factorial works) above we can say that 1! Or 0! Is pointless. Which means that their factorial result is pretty much the same as their own number (Like 1 x 1 = 1). That is why i used the ‘if’ statement.

Next the ‘else’. You can see that i created a function called factorial and inside the bracket (parameter) called val. Val here means value, so every number given will be stored in the val parameter and will be executed based on the return condition, let’s called it the factorial formula. So, the formula to factorial is every number given (val) will be multiplied with their original number that gradually decreased by one. As the code above i gave the val = 8, so the result should be

8 x 7 x 6 x 5 x 4 x 3 x 2 x 1

Notice that the number is decreased over and over until it reaches 1 (the smallest number possible).

And finally document.write is created to show and write the result of the code in your browser. You can also use console.log or just call the function which is in my case factorial(8) but to see it you need to open the console window in your browser. If you use chrome you can do this by hit the f 12 button or ctrl + shift + i buttons.

There you go, a simple factorial code. Look, i am still a beginner so please tell me if i made any mistake and hopefully my english is good, heeheee.

Allright! Looking forward to share another code here, have a good day!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s