×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

# Javascript Functions: Introduction

This article will give you an introduction about functions in Javascript language. We will talk about the definition and declaration of these functions.

0

### Introduction

A function is a set of instructions to perform a particular task. We can consider an example of scientific calculator. Most of these calculators have some special keys which are intended to do some more complex operations than normal addition or multiplication. For example, some calculators can calculate square or cube root of a very large number or provide statistical function to perform larger calculations. All of these operations can be performed using basic mathematical operations such as addition, multiplication etc. But it will take a lot of steps. For a casual user it is much easier to only provide the data, then wait some buttons and let the calculator handle all the complex operations rather than solving on his own. These buttons are the function keys.

Similarly, in programming, functions are used to perform some repetitive task. For example, parseInt() and parseFloat() functions which are used to convert string to numbers. If user wants to perform these tasks on his own then every time he has to write the whole code to perform these operations. But when he uses function, he has to provide the required data only and functions do rest for him. No need to worry about lengthy, unnecessary code.

Function is JavaScript are encapsulated block of codes to perform certain tasks. Some of these functions simply return some output, where other may simply perform the task and do not return any data. Some function allows the passing of data where other cannot. The data passed in a function is called parameters.

### Function Definition and Declaration

In JavaScript, creating a function is very simple. We can use a simple example, a very popular Fahrenheit-to-centigrade conversion code to describe a function:

Listing 1: Representing the example function

```function convertToCentigrade ( degFahren )
{
var degCent;
degCent = 5/9 * (degFahren - 32 );
return degCent;
}```

To define a function we use a keyword function and after then instantly provide unique name for that particular page. A programmer should use names, which reflects the task performed by that function so that when in future when he see it later, he can understand what it does. But a developer cannot use the JavaScript’s reserve word such as while() or with() as they will through an error.

A parameter can be passed in the parentheses given after the name of the function. A parameter is a data value which is needed to perform the task assigned to the function. If user will not pass the appropriate parameter in the function, it will cause an error. It is mandatory to put parentheses after the function name even if it has no parameters to pass. A function can pass zero or more than one parameters. Your function definition must look like this:

### function WithoutParameterExample()

After this function definition, the function code will come. This code is responsible to perform the intended task when function call is made and it should be assembled within a pair of curly braces.

Function may return a value to the calling code. For this purpose, a return statement is used. As in Listing 1, the function is returning the calculated value of degCent to the caller of this function. It is a good programing practice to always include a return statement in your function although you don’t want to return anything. But if you won’t, it will not cause any problem. When JavaScript encounters a return statement in a function, it exits the function while returning the value associated with return keyword. It is good to build a library of the frequently used function in JavaScript, so that you can use them in your page whenever you need them.

Function executes only when a function call is made or when something invokes the function. A function is called by writing its name at that point where user wants to use it and the required parameters should be passed, separated by commas. For example:

`myExample=convertToCentigrade(112)`

In this line, the function declared in Listing 1 is called with value 112 as parameter and then returning the answer(in this case, it is 80 ) to the variable myExample for further use.

Now, we create a simple function to make it more clear to you. In this function, you will create a simple function to take user’s name as function parameter and then writes it to a page in a welcome string. To do this, first choose a name which reflects the task of your function. In this case, we choose UserWelcome(). Now you should think about the parameters the function expects to be passed which is user name. You should follow proper variable naming conventions when assigning parameters name. We call our parameter UserName. We include our parameter inside the parentheses to the end of the function name:

After defining our function, now we include the code which will be executed when function is called. This is called body of the function.

Listing 2: Representing example of sample function

```function UserWelcome(UserName)
{
document.write(“Welcome Noob!!! “ + UserName + “<br />”);
document.write(“You should love coding!”);
}```

In this simple function, document.write() is used to write a welcome message to the web page. The value of the parameter will be specified where the function is called by JavaScript code.

To call this function, we use this line of code:

### UserWelcome(“Alok”);

To call this function, we just write the function name and pass the vale “Alok” to the parameter UserName.

Now suppose if you want to pass another parameter such as UserAge, then the Listing 2 code will slightly modified as follows:

```function UserWelcome(UserName, UserAge)
{
document.write(“Welcome Noob!!!” + UserName + “<br />”);
document.write(“You should love coding<br />”);
document.write(“Your age is “ + UserAge);
}```

To call this new function, we us this code:

`UserWelcome(“Alok”,25);`

The second parameter is a number or age of the user “Alok”.

### Complete JavaScript Function Example

This is a complete code of a simple JavaScript code to demonstrate the parameter and function. Save this code in a text editor, give it some name with .html extension and then load it in a browser. Your task is to find out how this code is working:

Listing 3: Representing the example JavaScript code

```<HTML>
<TITLE>Example of function and parameter in JavaScript</TITLE>
<SCRIPT  Language="JavaScript">
<!--
function ChangeExample(a){
a = 100
document.writeln("Inside the function A=: " + a)
}
//-->
</SCRIPT>
<BODY>
<PRE>
This code is check the value of a variable before and after the calling of a function.
<SCRIPT Language="JavaScript">
<!--
a = 20
document.writeln("Before calling the function variable A=: " + a)
ChangeExample(a)
document.write("After calling the function variable A=: " + a)
//-->
</SCRIPT>
</PRE>
</BODY>
</HTML>
```

The reason for not providing details about this code is because sometimes a new programmer must learn how to develop his programming concepts. A programmer must try to find his own solutions instead of copying someone else work and these type of exercises are very important for beginners.

### JavaScript functions

A user can use built-in functions of JavaScript in addition to custom developed functions. Some of these functions are given below:

• decodeURI(string): This function is used to decode the text strings encoded with encodedURL() function.
• decodeURIComponent(string): is used to decode the text strings encoded by encodeURLComponent()
• encodeURI(string): It encode a text string to a valid URL.
• encodeURIComponent(string): Encodes a text string to transform it in a valid URL component.
• eval(string): If an expression is contained within a string then this function evaluates it.
• isFinite(number): This function determines whether a number is finite.
• isNaN(number): This function is used to determine whether a value is NaN (Not a number).
• parseFloat(string): This function convert string values to float.
• parseInt(string): This function is used to convert string to integer.

### Conclusion

As we learned in this conversation, functions are very important part of JavaScript because they make coding easier and provide reusability of the code. JavaScript provides a lot of built-in functions as well as it provides facility to create custom functions to perform user specific tasks. Function may allow to pass one or more parameters and sometimes they will not allow any parameter to pass. They may return a value or may not as par demand of the coder.

Have total 6+ years of experience in developing enterprise applications using DOT.NET 3.5 and 4.0(C#, VB.NET, ADO.NET, ASP.NET),java, JQuery, JSON, LINQ,WCF, MVC3, MVC4, Silverlight, SQL Server, mobile applications and Oracle etc ...

What did you think of this post?
Services

Related Posts

[Close]

See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US\$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US\$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US\$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!