The concept of function comes into Javascript to support the way we organize and structure code. A function is a block of code that performs a specific task and we can reuse the function throughout the program.
In function, we can easily change or update function behaviour by modifying the program. Additionally, by using functions we can make code more readable and easier to understand.
In JavaScript, there are some in-built functions which can be directly used and some are user-defined.
There are several types of functions in Javascript.
Expression Function: In this function, the user defines a function and assigns it to a variable. The syntax is quite different from the function declaration.
Syntax:
// Function Expression
let variableName=function(){
console.log("shushil chaubey");
}
variableName();
Anonymous Function: Anonymous, is something that does not have any "name" or "identity". Similarly, anonymous functions in JavaScript are functions that do not have any name.
Syntax:
// Function Expression
let variableName=function(){
console.log("Hash Node");
}
variableName();
Arrow Function: In this function, we use an arrow and callback. Arrow functions can be written in different ways depending on the number of parameters it accepts and the operation it performs.
Syntax:
// Arrow Functions
const sumoftwoNumberm = (x,y) => x+y;
console.log(sumoftwoNumberm(12,12));
Some codes are related to the function.
// Function with Parameter
function add( a, b){
return a+b;
}
let result=add(3,4)
console.log(result);
// array Parameter
function Arrayparameter([num1,num2]){
return num1+num2;
}
let res1=Arrayparameter([10,30])
console.log(res1);
function passMessage(){
return "I am Happy to learn Full stack";
}
let res2=passMessage();
console.log(res2);
let newMessage= res2+" Enroll Today"
console.log(newMessage);
// self invoking Function
(function (x){
console.log(x);
})("Welcome to Pw sills")
const sumAnd_Differnece=(x,y)=>({sum: x+y , difference: x-y})
console.log(sumAnd_Differnece(10,8));