What is a Function?
- A function is a block of code or a subprogram designed to perform a particular task.
- Function is executed only when it is called. This is called invoking/calling a function. Thus it eliminates writing the same code again and again.
- Values can be passed into functions and used within the function body.
Function always returns a value, if no return type is specified, the function will return undefined .
JavaScript Function Syntax
1 2 3 | function <function name>(parameter1, parameter2, parameter3,….) { // code to be executed } |
JavaScript supports 4 types of function invoking:
- Function having no arguments and no return value
- Function having arguments and no return value
- Function having return value and argument(s)
- Function having return value but no arguments
Function having no arguments and no return value
In JavaScript, if there’s no specified return type, the function will return undefined. Consider the following example:
1 2 3 4 5 6 7 8 9 10 11 | <html> <body> <script> function myFunction() { alert("Within myFunction!"); } </script> <input type="button" id="test" onClick="myFunction ()"> </body> </html> |
Result
1 | Within myFunction! |
Function having arguments and no return value
Consider the following example:
1 2 3 4 5 6 7 8 9 10 11 | <html> <body> <script> function myFunction(x, y) { alert(x + y); } </script> <input type="button" id="test" onClick="return myFunction (2,3)" /> // Function is called </body> <html> |
Result
1 | 5 |
Here the ‘return’ statement is missing. But arguments are passed to the function and used in the block of code.
Function having return value and arguments
1 2 3 4 5 6 7 8 9 10 11 | <html> <body> <script> var a = myFunction(2, 3); // Function is called, return value will be stored in x function myFunction(x, y) { return x + y; // Function returns the summation of x and y } </script> </body> </html> |
Result
1 | 5 |
Function having return value but no arguments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <html> <body> <script> var z = myFunction(); // Function is called, returned value will be stored in z alert(z); //Output: MyFunction function myFunction() { return "MyFunction"; // myFunction returns the specified string } </script> </body> </html> |
Result
1 | myFunction |