Function
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again.
Functions are called first class functions or citizens in javascript because it has the ability to act as values to a variable, pass them as arguments in another function and return them in another function.
Function declaration or Function statement
The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
Example :
Calling a Function
To invoke/call a function, simply need to write the name of that function. The function will execute the code after you invoke it.
Example :
Function Parameters
We can pass parameters while defining a function with in paranthesis and pass arguments while invoking. A function can take multiple parameters separated by comma. Check out the example:
Example :
The return Statement
The return statement is required if you want to return a value from a function. This statement should be the last statement in a function. By default, function returns undefined .
Example :
In above example, after the add(5, 4) completes its execution returns the value 9 and that value should be stored in a variable (res).
JavaScript anonymous functions
An anonymous function is a function without a name. An anonymous function is often not accessible after its initial creation.
The following shows an anonymous function that displays a message:
In this example, the anonymous function has no name between the function keyword and parentheses ().
Using anonymous functions as arguments of other functions
In this example, we pass an anonymous function into the setTimeout() function. The setTimeout() function executes this anonymous function one second later.
Function Expression
A JavaScript function can also be defined using an expression.
Initialition of anonymous function to a variable is called function expression.
Example :
Immediately Invoked Function Expression (IIFE)
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
If you want to create a function and execute it immediately after declaration, you can use the anonymous function like this:
First, the anonymous function with lexical scope enclosed within the Grouping Operator ().
Second, the trailing parentheses () calls the function.
Example :
Call back function
Call back function is an function passes in to another function as an argument
Example :