Updated on Kisan Patel
JavaScript functions provide a way to encapsulate a block of code in order to reuse the code several times.
To define a function, we use a reserved keyword function
and write function name. The block of code that we want to execute inside the function is written under the opening {
and closing curly braces }
.
Syntax
function functionName(parameters) { code to be executed }
Here is the simple example of parameterless function:
<!-- JavaScript --> <script language="javascript" type="text/javascript"> function simpleFunction() { alert("I am displaying from alert method"); } </script> <!-- HTML --> <input type="button" id="btnTest" onclick="simpleFunction()" value="Click me to Alert!" />
In above code snippet, the alert message will be displayed only when the “Click meto Alert!” button will be clicked as simpleFunction()
function is being called on click of this button.
See the Pen YXMxWP by Kisan (@pka246) on CodePen.
Here is another example of javascript which accepts parameters and return the result.
See the Pen BNEdLp by Kisan (@pka246) on CodePen.
Function parameters are a way to pass data to a function. The parameters are separated by commas and included in the parentheses following the function name.
makeHello(firstName, lastName);
The function then processes the parameters, as needed.
function makeHello(firstName, lastName) { alert("Hello " + firstName + " " + lastName); }
Data is returned from the function to the calling program using the return statement.
function makeHello(firstName, lastName) { return "Hello " + firstName + " " + lastName; }
You can pass several parameters to the function, but only one return
value.