Programming Functions


What is a function in programming?

A function is a block of code that performs some action. The statements written in the function are executed when it is called by its name. We write functions because a program may need to repeat the same piece of code at various places.

Advantages of using Functions

1- Easier to code 2- Easier to Modify 3- Easier to maintain 4- Re-usability 5- Less programming time

Two types of functions

1- Bulit-in function

Those function that are available as a part of language is known as built-in functions or library function. These are provided by the language that we are using. These function provide the programming easier. For Example: An pop up alert function by JavaScript. <script type="text/javascript"> alert('Hello World !'); </script>

2- User Defined function

Those functions that user define to solve particular problem are the user defined functions.A user defined functions consists of following. 1- Function declaration. 2- Function Definition or block of statements.

Syntax of Functions in JavaScript

function function_name() { statement; }

Write a user defined function to alert a message using JavaScript alert function.

<script type="text/javascript"> function WelcomeFunction() { alert("Welcome to Coding JavaScript Tutorial Series"); } </script>

How to call the JavaScript function?

JavaScript function can be called by different methods , we will discuss few methods here.

<button onclick='WelcomeFunction()'>Click me </button> <a href="javascript:WelcomeFunction">Click me</a>

Full Program Source Code to create and call function

Output : Click me <html> <head> <title> Java Script Functions </title> </head> <body> <script type="text/javascript"> function WelcomeFunction() { alert("Welcome to Coding JavaScript Tutorial Series"); } </script> <a href="javascript:WelcomeFunction()">Click me</a> </body> </html>
Chapter Next »