Function
Function
A Function is a reusable block of code which is designed in order to perform the particular task as many as you want.
Mainly, it is defined as a block of code which is used over and over again when needed. This block of code is only executed only when it is called.
With the help of functions, we eliminate the need for writing the same code again and again.
In order to define a function in javascript, we use the function keyword, followed by a unique function name, followed by a set of parentheses () which may include parameters names that are separated by commas.
Finally, the code to be executed by the function is placed inside the curly brackets {}.
Syntax
function functionname (parameter 1, parameter 2, parameter 3)
{
Block of code to be executed
}
Calling a Function
By calling the function we actually execute the block of code which is written inside the function with the indicated parameters.
We can pass not only the strings or the numbers as a parameter, we can also pass the whole object in a function.
To call a function, we have to start with the function name, then follow it with the parameters in parentheses.
Syntax
function functionname ()
{
Block of code
}
functionname ();
// calling a function
Once the function is defined, we call it as many times as we want to.
Code:
<html>
<body>
<h2>The function</h2>
<script>
function demo()
{
document.write("Block of code get executed when called."+ "<br>");
}
demo();
demo();
</script>
</body>
</html>
In the above example, we have defined a function named demo that has a block of code which displays a message.
This function can be executed only if when it is called by the user.
Output: