-1

Which is is the best way to define a function in javascript . how to define a function using ':' like function_Name : function(){} .

4
  • You can't define a function like function_Name : function(){}. It needs to be function function_Name(){} or var function_Name = function(){} Commented Sep 7, 2016 at 10:14
  • You mean var anyFunctionName = function(){} and function(){} Commented Sep 7, 2016 at 10:17
  • 1
    Check this answer - stackoverflow.com/questions/336859/… and this davidbcalhoun.com/2011/… Commented Sep 7, 2016 at 10:18
  • Please take note that in standard international English questions are followed by a question mark (with no intervening space). Sentences start with a capital letter. Code in your question should be surrounded by backticks to make it formatted properly. You need to apply the same attention to detail in writing your question as I know you apply in your programming work. Commented Sep 7, 2016 at 11:38

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

3 Comments

I think you left an extra } in your example of IIFE
@GibboK thanks for pointing out the mistake. I have edited it
Why would he look at call and apply? They are ways to invoke functions, not define them, which is what his question was about.
-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.