A function is a group of code statements which performs some specific task by taking some input or without any input. A function may return some output to the user or can do computation to result in some output..
The basic idea of the function is to reduce the amount of code and executing a code block whenever needed.
- function starts with function keyword
- Then the name of function is written after a space. Function name follow same rule as variable name
- then a list of parameters are given, enclose in parentheses and separated by commas (number of parameters could be any starting from 0)
Here is an example of a function that is invoked when a button is clicked.
Just defining a function does nothing. It must be invoked/called.
function does nothing until it is invoked. function can be invoked in following ways:
- Invoking function when some event occurs in the webpage. Example button click, mousemove, page load etc
- Self invoking function. function calls itself also known as recursion.
Lets see an example for all kinds of function calls.
Direct function call
function call by an event
Self calling function
function parameters are the values that are taken when the function is called.
Parameters are extra added information that is required and used in the function while execution of the code.
The actual values that are passed in the function are known as arguments while the variable that is declared in the function is known as parameter.
Lets see an example where function is using argument.
Function using arguments
In the functions we can pass more or less arguments than the defined parameters.
- When number of arguments are less than parameters then rest parameters will be undefined
- When number of arguments are more than parameters then extra arguments will be ignored
Lets see an example to understand.
Function using less or more arguments
Function Return Value
function can return some value when called. Generally some kind result is returned from the function. To use the return value function is assigned to some variable.
To return something from the function
return keyword is used with the return value separated by space.
Function stop execution when reached to
The variables that are defined inside the function have local scope. These variables can't be accessed outside the function.
But function can access the variable defined outside the function.