JavaScript function

      No Comments on JavaScript function

A JavaScript function is a block of code designed to perform a particular task.

A function is more generally a subprogram which is called.

For efficiency of any pages, the repeated cclock of lines are combined in a fucntion which can be called any where and as many as times required. Function perform the task they are told to do.

Function do not come into action on there own. They have to invoked or called.

Syntax
function function_name(parameter1,parameter 2..)
{
//statements
}
    Javascript Functions begins with a function keyword, followed by the function name.The parentheses may include parameter names separated by commas:(parameter1, parameter2, …).
    Function parameters are the names listed in the function definition.Function arguments are the real values received by the function when it is invoked.Inside the function, the arguments (the parameters) behave as local variables. The code to be executed is placed inside the blocks {}.

How is the Function Invoked?

The code inside the function will execute when “something” invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

Return statements

When the script reaches a return statement, the function stops executing.Functions often compute a return value. The return value is “returned” back to the “caller”.

Usage:

<script>
<p id="demo"></p>
function myfun(a,b)
{
 return a+b;
}
document.getElementById("demo").innerHTML = myFunction(14, 40);
</script>

Output:

One more example
<script>
function alertfunction()
{
alert("hello");
}
</script>

Output:


Other example
<script>
function toCelsius(f) {
    return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
</script>

Leave a Reply

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