Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Robert Stefanic
35,170 PointsWhat are the advantages to defining a function as a variable in JavaScript?
So I see people who define their functions as variables in JavaScript. Why would you do this?
So there's this way of defining a function:
function newFunction() {
//Code
}
and this way:
var newFunction = function() {
//Code
};
The only difference I can really see is that, in the first example, you can call a function at anytime as long as it's defined somewhere in the document, where as if you wanted to define a function as a variable, like in the second example, it'd need to be defined before you called it -- but why would anyone do that? It just seems like the second method takes longer and is a more complicated way to define a function.
Thanks.
1 Answer
Steven Parker
243,318 PointsYour observation is true for most simple cases. But there are times when second form is required, such as when a function is defined by calling another function which returns a function. Or the variable being assigned may have a special scope. Or something else about the assignment differs from what a normal function declaration would do.
You'll probably never need to use the second form yourself until you have learned the specific reason for why it is required in the situation you are programming.
In existing code, you'll need to examine each situation to see if it was used by necessity or just the author's preference.
Robert Stefanic
35,170 PointsRobert Stefanic
35,170 PointsI see. I don't know if I quite understand the nested example, but I do get the special scope one (like if a function is defined in another function).
For now, I don't see a reason for defining it the second way, and I guess until it comes up, I won't fret about it too much.
Thanks for your reply!