Function
Function is a block of code designed to perform a specific task. It executes only when it is called (invoked).
Syntax
function functionName() {
// Code to execute
}
- Code reusable
- Declare code once,use it whenever we want
- Call the function to execute the code
*call Function *
function sampleFun(){
console.log(2+3);
}
sampleFun()
Output:5
Function Parameter
Parameter- It is a variable declared in a function definition that receives the values passed to the function when it is called.
Argument- It is the value supplied to a function's parameter during a function call.These values are received by the function's parameter.
function sampleFun(a,b){
console.log(a+b);
}
sampleFun(10,20)
Output:30
Function Return
Used to end function and send value back to the place where the function was called.
function sampleFun(a,b){
return a+b;
}
var x=sampleFun(10,20)
console.log(x)
// console.log(sampleFun(10,20))
Output:30
Anonymous Function
- Function without a name
- Function is stored in a variable
var sampleFun=function(){
console.log("Hello World");
}
sampleFun()
Output:Hello World
Callback Function
Function passed as an argument to another function ,which is called after a specific task is completed
function mainFun(callback){
console.log("main function executed");
callback()
}
// console.log(callback)
function callback(){
console.log("callback function executed");
}
mainFun(callback)
// callback()
Output:main function executed
callback function executed
Self-invoking Function
OR IIFE-Immediately Invoking Function Expression
Function that executes automatically as soon as it is defined or created
(function() {
console.log("Self-invoking function executed");
})();
Output:Self-invoking function executed
Arrow Function
- Arrow Functions allow a shorter syntax for function expressions
- Can skip the function keyword, the return keyword, and the curly brackets
var sampleFun = () => {
console.log("Arrow function executed");
};
sampleFun();
Output:Arrow function executed
const multiply = (a, b) => a * b;
console.log(multiply(5, 5));
Output:25
Top comments (0)