Skip to main content

JavaScript Functions

[3/100]

Today was busy and I had an only an hour or so in the evening to sit down and continue JS overview. I did additional small work on Wix but cannot really call it coding... I gave myself a promise and even if it means giving it only 5 minutes I am gonna write a line of code everyday.

I am continuing Colt's bootcamp on Udemy. We have been going over JS functions and their structure which is:
function function_name(argument/empty) {
doSomething;
}

There are also two ways of defining a function:
  • Function declaration 
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
  • Function expression
var capitalize = function(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

I am familiar with the concept and the exercises went pretty smoothly, however I had a tough time with writing a function that was supposed to return a factorial of a number. I could not figure out how it should be done and after multiple attempts I turned to Google for a solution. I am not sure if in this case an obstacle were my math skills? Colt explained a concept of factorial beforehand and I understood the principle of it however I could not translate it into the code. Making things worse, the solution I found is not telling me what exactly is happening and why this approach was used. I still haven't heard Colt's take on it so hopefully it will become more clear. 

The solution I found:

I won't move on from it till I am confident I get it fully. I don't want to just write code that works I want to write code that I understand completely too.

Update

Since it was sitting on my mind, I researched the factorial issue and found this explanation on Stack Overflow. From what I understand the function iterates through itself with  return x * factorial(x-1) till it reaches true in the if statement. The concept presented in this solution is called Recursion and I found this article that goes more in depth into it. 

Colt presented a different solution to this problem: 


This is the direction I was going to initially trying to solve it with using a for loop but the part I was missing was a declaration of a variable in the function. 

Colt's code is more clear and uses the concepts he already covered in the course which makes sense that he would write it this way. However, the answer with a more advanced approach of using a recursion seems to be the most popular from my quick research into factorials. 

On FreeCodeCamp I found an article on additional three possible ways of writing factorials and a great explanation of how to approach this problem.  

The bottom line is (and this is just after covering basic concepts) that what fun and at the same the most challenging is about JS is that it can be written in so many ways while maintaining the same results. It gives you so much freedom to experiment with it, which you need to understand first to really enjoy.   

Comments