Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Var functionName = function() {} vs function functionName() {}

I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.

The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.

The two ways are:
var functionOne = function() {
// Some code
};


function functionTwo() {
// Some code
}


What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?
by

2 Answers

akshay1995
An illustration of when to prefer the first method to the second one is when you need to avoid overriding a function's previous definitions.

With

if (condition){
function myfunction(){
// Some code
}
}

, this definition of myfunction will override any previous definition, since it will be done at parse-time.

While

if (condition){
var myfunction = function (){
// Some code
}
}

does the correct job of defining myfunction only when condition is met.
RoliMishra
An important reason is to add one and only one variable as the "Root" of your namespace...

var MyNamespace = {}
MyNamespace.foo= function() {

}
or

var MyNamespace = {
foo: function() {
},
...
}

There are many techniques for namespacing. It's become more important with the plethora of JavaScript modules available.

Login / Signup to Answer the Question.