Declaring functions in JavaScript

JavascriptSyntaxFunction

Javascript Problem Overview


What's the difference between these two ways of declaring a function?

function someFunc() { ... }

var someFunc = function() { ... }

I'm not asking in the technical sense. I'm not asking which is better for readability, or which style is preferred.

Javascript Solutions


Solution 1 - Javascript

I am on different opinion with most of the people here. Technically this syntax may mean the same for declaring functions both ways (I stand incorrect on my last statement. I read up on a diff post why they are technically diff and I'll add in the end, why) ; but the way they play a role in evolving patterns is massive. I would highly recommend "Javascript: The Good Parts" by Doughlas Crockford.

But to prove my point in a subtle and a simple manner; here is a small example.

//Global function existing to serve everyone
function swearOutLoud(swearWord) {
    alert("You "+ swearWord);			
}
//global functions' territory ends here
	
//here is mr. spongebob. He is very passionate about his objects; but he's a bit rude.
var spongeBob = {
    name : "squarePants",
	swear : function(swearWord) {
	            name = "spongy";
				alert("You "+ swearWord);
			    return this;
			}
}
	
//finally spongebob learns good manners too. EVOLUTION!
spongeBob.apologize = function() {
    alert("Hey " + this.name + ", I'm sorry man!");
	return this;
}
	
	
//Ask spongebob to swear and then apologize in one go (CASCADING EFFECT!!)
alert(spongeBob.swear("twit").apologize());

if you look at the code above I declared a function with a name swearOutLoud. Which would take a swear word from any object or a call and will give you the output. It can do operations on any object using the "this" parameter that is passed to it and the arguments.

However second declaration is declared as an attribute of object called "spongeBob". This is important to note; as here I am moving towards an object driven behavior. While I am also maintaining "cascading effect" as I return "this" if i have nothing else to return.

Somthing similar is done in jquery; and this cascading pattern is important if you are trying to write a framework or something. You'll link it to Builder design pattern also.

But with functions declared as an attributes of an object I am able to achieve an object centric behavior which leads to a better programming paradigm. Unless designed well; individual functions declared outside with global access lead to a non-object oriented way of coding. I somehow prefer the latter.

To see cascading in effect, look at the last statement where you can ask spongebob to swear and apologize at once; even though apologize was added as an attribute later on.

I hope I make my point clear. The difference from a technical perspective may be small; but from design and code evolution perspective it's huge and makes a world of a difference.

But thats just me! Take it or leave it. :)

EDIT:

So both the calls are technically different; because a named declaration is tied to global namespace and is defined at parse time. So can be called even before the function is declared.

 //success
 swearOutLoud("Damn");

function swearOutLoud(swearWord) {
    alert("You " + swearWord)
}

Above code will work properly. But code below will not.

swear("Damn!");
    var swear = function(swearWord) {
	console.log(swearWord);
}

Solution 2 - Javascript

One advantage of using function someFunc() { ... } is that the function name appears in Firebug debugger. Functions that are declared the other way (var someFunc = function() { ... }) come up as anonymous.

Solution 3 - Javascript

Actually, the difference is that the second declaration gives us the ability to declare functions like this making it possible to have a function as a property for an object :

var myObject=new Object();
myObject.someFunc=function() { ... }; 

Solution 4 - Javascript

Style wise the second example is more consistent with other common ways to declare functions and therefore it could be argued that it is more readable

this.someFunc = function() { ... }
...
someFunc: function() { ... },

However, as also mentioned it's anonymous and therefore the name does not appear when profiling. Another way to declare the function is as follows which gets you the best of both worlds

var someFunc = function someFunc() { ... }

Solution 5 - Javascript

Another difference is that, on most browsers, the latter allows you to define different implementations depending on circumstances, while the former won't. Say you wanted cross-browser event subscription. If you tried to define a addEventListenerTo function thusly:

if (document.addEventListener) {
    function addEventListenerTo(target, event, listener) {
        ....
    }
} else if (document.attachEvent) {
    function addEventListenerTo(target, event, listener) {
        ....
    }
} else {
    function addEventListenerTo(target, event, listener) {
        ....
    }
}

on some browsers, all the functions end up being parsed, with the last one taking precedence. Result: the above just doesn't work. Assigning anonymous functions to variables, however, will work. You can also apply functional and basic aspect oriented programming techniques using anonymous functions assigned to variables.

var fib = memoize(function (n) { 
    if (n < 0) return 0;
    if (n < 2) return 1;
    return fib(n-1) + fib(n-2); 
});

...
// patch the $ library function
if (...) {
    $ = around($, fixArg, fixResult);
}

Solution 6 - Javascript

It is both true that the first form:

function test() { }

is a more recognized syntax and that the second form:

var test = function() { ... }

allows you to control the scope of the function (through the use of var; without it, it would be global anyway).

And you can even do both:

var test = function test() { ... test(); ... }

This allows you to define a recursive function in the second form.

Solution 7 - Javascript

When you write

function Test() {
}

JavaScript is really creating a property to which it assigns the function object that once called will execute the code reported in the function definition. The property is attached to the object window, or to the object that contains the function definition.

Solution 8 - Javascript

For readability, I'd say the first is clearly better. A future maintenance programmer, even assuming they're familiar enough with javascript to know many of the finer points coming up in this thread, are going to assume the first format.

For example, if they should some day want to ctrl-f to search for the definition of your function to see what's happening in there, are they going to first search for someFunc = function() or function someFunc()?

Also, to get downright typographical about it (since we're talking readablity) readers are often scanning the text quickly, and would be more inclined to skip over a line that starts with "var" if they're looking for a function definition.

I know this is a non-technical answer, but it's harder for humans to read code than computers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnicholaidesView Question on Stackoverflow
Solution 1 - JavascriptPriyankView Answer on Stackoverflow
Solution 2 - JavascriptIgor ZevakaView Answer on Stackoverflow
Solution 3 - JavascriptSoufiane HassouView Answer on Stackoverflow
Solution 4 - JavascriptfrglpsView Answer on Stackoverflow
Solution 5 - JavascriptoutisView Answer on Stackoverflow
Solution 6 - JavascriptEMKView Answer on Stackoverflow
Solution 7 - JavascriptapadernoView Answer on Stackoverflow
Solution 8 - JavascriptPaul DegnanView Answer on Stackoverflow