Monday, 20 May 2013

Javascript functions - Basics

Hi there

This blog will sum up various methods of using JavaScript functions.

Firstly, what is a function?
It is a piece of code that is called by name. When it is called, the coding inside it will run. The purpose of this is to be able to call one method several times, if needed, without having duplicates of the same coding.

Example:

Lest say you have two close buttons( cancel and close button in top right corner ) on a popup.
They will both close the popup, but with some other code that may differ.

Here are the buttons calling different functions:

The functions which are being called are closePopup and cancelPopup.
The function looks as follows:
As you can see there are similarities between the two functions which is that both have the following:
Instead of using one line multiple times, you can take that line and put it in a seperate function, although for one line of coding, it's not worth the trouble, but when you have more code that is similar, you can do this.


In above method, if you call the hidePopup function, only the element with id popup will display as hidden. If you want the current object to hide or to change the styles, you can do the following:

As seen above, all the methods has an argument. That is merely the id of your clicked button. An argument is a value that is added into the functions parentheses to be used for some calculations.

Lets say I have

var x = 1;

Now I want to use that value in my method to return another value. The method will be called like this (Keep in mind that the variable name is x):

myFunction(x);


This function can either return a value or perform some actions. In the previous example where I used closePopup, they merely perform an action. With a return function, you can set a variable equal to the function like so:

As seen above, newVlaue is being set to function calculate. While you set this, the value x is sent to the function and is used inside the function as numberValue. In other words, when you're inside calculate, numberValue value is the same as the value of x. I have explained what the while loop does here.

Lastly we see the code return numberValue; What this does is it send back the final value, where it is then stored in newValue. Thus the line
var newValue = calculate(x);
can be read as
var newValue = 16;

For further questions or if you want a tutorial for something, leave a comment or send me an email.

No comments:

Post a Comment