JavaScript Functions Simplified; The Best Explanation of functions

There are lots of explanations and tutorials about Javascript and specifically functions out there which we all may have tried. But thus far from all I have seen, a unique approach around the whole language is what Gordon Zhu has implemented in watchandcode.com  that is a practical way and very deep understanding of every major part of JavaScript.

I will explain functions here as my own take away which I hope be helpful to you too.

Just imagine  a resturant menu which probabley would have lots of different foods with their own receipies. Although each food would have its own recepie but each category of food will have a similar one.

For example, seafoods would have quiet similar recipe but different ingredients. So in the kitchen, they will use similar “process” with their own “steps” and they will make the dish accordingly.

We would write the “process”  and its “steps” and we can write a recipe like this:

  • Add the ingredients
  • Cook the Food 

As you see, the whole process contains a few steps depends on the food that needs to be made.

**Functions in JavaScript are the same. As their name suggest, they function or do something in one or more steps. They might need some inputs like ingredients in our food recipe and they might have an output like serving the food here. **

Now lets write our own recipe in a function format.

First we need the Function word in the beginning as specifier of the “Process” following by the name of it as what it does. In order to make the function be able to take inputs which are called arguments,we need parntheses in front of function name and the whole process would be wrapped in curley braces:

Function makeSeafoood (ingredients){

  • Add the ingredients
  • Cook the Food 

}

And this is a function. Of course it is not a JS valid code yet, but it is pretty much the fundamental of a function.

Let’s make it all valid code then.

First, we used ingredients as the input of the function, but we know it contains lots of tings so we could use an array of various ingredients to specify it. And in JavaScript we declare variables like this:

var ingredients = { ‘item1’, ‘item2′ ,’item 3’} // like rice, fish, onion ,….

Now ingredients have been specified. Now we use the action “cook” as the actual statement inside the function and add the ingredients as expected:

Function makeSeafoood (ingredients){

Cook(ingredients);

}

It is that simple. Now we have a function based on our example which in a real world we will make it functional but the concept which was our goal remains intact.

Hope it has been useful to you.

© 2020
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.