Which is is the best way to define a function in javascript . how to define a function using ':' like function_Name : function(){} .
2 Answers
Hope this will be useful
Named function
function someName(){
//rest of code
}
can be called by someName();
Function expression
var someName = function(){}
can be called by someName()
IIFE
(function(someParam){
//rest of code
}(params))
IIFE can also can also written in this way
+function(someParam){
//rest of code
}(someParam)
Named function expression
var someVar = function someFoo(){};
this is called by someVar() . someFoo is only accessible inside itself
Arrow function(aka fat arrow)
var someVar= (param1, param2) => {return somereturn}
Function constructor
var adder = new Function('a', 'b', 'return a + b');
Beside this you can also take a look at call & apply
There is no "best" way to define a function, it depends on your needs. For example if you have a function that validates something it makes sense to put it into a variable like Pugazh said:
var foo = function(){
if (/*some condition*/) {
//do something...;
return true;
}
else {
return false;
}
And then use it like alert(foo()); and it will execute the function and return the value (true or false).
Sometimes you want a named function you can call with options like:
function SaveData(data) {
//Code to save something
}
And then call it like SaveData("Hello World");
And sometimes you just add a function without a name that is executed as a callback (e.g. in jquery) or when you perform a specific action but you define it at the event and not as a named function.
All types of functions have their use cases.
function_Name : function(){}. It needs to befunction function_Name(){}orvar function_Name = function(){}var anyFunctionName = function(){}andfunction(){}