Wednesday, August 20, 2014

Lesson 6 -- Fucntions

Today we will learn about Functions in Javascript. If you are coming from a programming background you will be well versed with the concept. If you don't, well nothing to worry about. It's really a simple but very important aspect of Programming.

To define,
A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it).
In layman terms,


A JavaScript Function is basically a mini-program written inside our Program which doesn't execute automatically. We have to call(invoke) it in order to do what it is supposed to do.
Still confused? Let's see an example to understand it in a better way.


I m sure you guys must have a Television (TV) at your home. So, to switch on the TV you press the Power button on the remote, right? So what it does is, when you press the Power button, it invokes a specific function (mini-program) to send the Signal to TV via infrared to Power On. Similarly when you press other buttons like Volume+/Volume-/Channel/Channel-, Remote is preconfigured to invoke only feature specific function and send it to TV in form of Signal.
I hope the example made you aware of how functions work. You can also relate it with example of Calculator where every button is assigned to do a task (function). 

Let's see the Syntax of a Function:
function <function_name>(<parameters>)
{
         <Statements>;
}
To understand it in a better way, let's see the following:

Code:
Output:
See! pretty awesome right? Now, you will ask how did we invoked it? Well you see that greetings( ); statement did the magic. Since the program executes from Top to Bottom, it went down from function declaration and did nothing, but when it reached the invoke part(known as calling the function), It will go back to the function (greetings( ); in this case) and will execute all the statements between it.

Now, Lets do some HTML magic ;) I told you in Lesson 0 that I will assume you have basic xHTML knowledge. So what we will do is, we will create a Button which will tell us "You are AWESOME!" everytime we will click it. Sounds amazing right? Let's see the code:

Code:
Output:
Click the Button


Voila!
Possibilities with the Functions are endless. It is one of the core concept of the Programming languages. Now here is one DIY for you.

#DIY-3
Make a function and use variables and strings along with buttons to print out your statements (invoke the function).

Just try it yourself and then you will get the concept of it. Functions are really easy to use and are very helpful to call repetitive statements just by invoking it. I hope, I didn't confuse you guys. Please try and post your doubts, if any. That's all for this lesson. Peace.

No comments:

Post a Comment