Posted By:
26 Aug, 2014 11:02 am PDT

Parameterized functions in JavaScript

  So, now I have understood a simple function.

  • Please help me understand functions with parameters.
  • And if I want to return something, how do I do it?
Attachment:None


JavaScript Functions with Parameters

A function can take multiple parameters separated by comma.

Example:

Let us do a bit modification in our sayHello function. This time it will take two parameters:

<script type="text/javascript">

<!--

function sayHello(name, age)

{

   alert( name + " is " + age + " years old.");

}

//-->

</script>

 

Note: We are using + operator to concatenate string and number all together. JavaScript does not mind in adding numbers into strings.

Now we can call this function as follows:

<script type="text/javascript">

<!--

sayHello('Zara', 7 );

//-->

</script>

 

The return Statement:

A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.

For example you can pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program.

Example:

This function takes two parameters and concatenates them and return resultant in the calling program:

<script type="text/javascript">

<!--

function concatenate(first, last)

{

   var full;

 

   full = first + last;

   return  full;

}

//-->

</script>

 Now we can call this function as follows:

<script type="text/javascript">

<!--

   var result;

   result = concatenate('Zara', 'Ali');

   alert(result );

//-->

</script>

 
Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud