Functions in JavaScript:

A function is a code which can be used any where in your programming means function is a reusable code. The main purpose of creating functions in your programme is to divide your big programme in manageable and small functions.

JavaScript has their some own predefined functions like alert(), write(), etc. and also user can define his functions.

Syntax:

To create a function first of all we need to define that function and for that “function” keyword is used and than the “function name” that is may be user defined or predefined JavaScript function and after that we have to write opening braces and closing braces like “()”. This symbole indicates that it is a function. After naming function you have to start the function with opening curly braces “{“and end the function with closing curly braces “}”.

Below is the basic common syntax of function in JavaScript:

<script type=”text/javascript”>

function functionname(parameters)

{

Statement to be executed

}

</script>

Example:

This is a very simple example of function. Here we created our own function “myFirstfunction()” and also use predefine function “alert()”

Functions with Parameters:

In above example we have seen that the function is without parameters. But in JavaScript you can define a function with parameters also. You can assign multiple parameters to a function and use it later in your programming.

Example:

Function with “return” statement:

JavaScript supports return statement in your function and it is optional. But if you want to return a value from a function at this time return statement is required.

To return a value from function you have to write “return” keyword before that.

Note: One thing you have to notice that return statement should be your last statement in function.

Example:

 

Leave a Reply

Your email address will not be published. Required fields are marked *