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 number of repeated code blocks and executing a code block whenever needed.
- Start function with
- Then write the name of the function after a space. The naming convention of function is same as variable naming convention.
- then a list of parameters are given, enclose in parentheses and separated by commas like (parameter1, parameter2, ...)
function declaration syntax:
Here is an example of a function that is invoked when a button is clicked.
As we have seen above function is a statement, but we can also make function an expression.
A function expression can be anonymous, it does not have a name.
A function expression is convenient when passing a function.
Just defining a
function does nothing until it is invoked or called.
Direct function call
In the following example we have a function that alerts a message, it is invoked as page loads and when button is clicked.
Note: We can call a function from any event we want and as many times.
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.
- 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 can return some value when called. To use the return value function is assigned to some variable and when function return some value it get stored in the variable.
To return something from the function
return keyword is used with the return value separated by space.
Function stop execution when reached to
return value can be placed anywhere in the function but as soon as function find return statement it stops further execution of the code in function.
Also, you can use
return statement without returning any value, you can do this to stop function to execute further in certain condition.
The variables that are defined inside the function have local scope. These variables can't be accessed outside the function.
But a function can access the variable that are defined outside the function.
- A function can have any number of arguments starting from 0.
- As soon as function reaches
returnstatement it stops further execution of it.
- Variable defined in a function has local scope.