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

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Introducing Functions

Philip Kroupoderov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Philip Kroupoderov
Front End Web Development Techdegree Graduate 21,641 Points

Any particular reason for using anonymous functions??

Are there certain situations where it's better to assign a function to a variable than it is to simply declare a function, or in all cases it doesn't matter??

1 Answer

Steven Parker
Steven Parker
231,268 Points

The main difference is that an assignment happens when the code is encountered, but a function definition is hoisted, meaning that the function would be available for use before the definition occurs in the code:

var x = add3(10);                   // this is fine
function add3(a) { return a + 3; }  // because this is hoisted

var y = sub2(10);                   // but this is a syntax error
var sub2 = a => a - 2;              // because this is not hoisted

One of the handiest uses for anonymous functions is as callbacks, where they are being passed as arguments and don't need to be used anywhere else in the code.

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

Didn't got that. Can you elaborate it more simply? I don't think I am familiar with the word "hoisted" . What does it mean . In first case , you have used the syntax of named function but in second case you have not used the syntax of "Anonymous function". Why?

Steven Parker
Steven Parker
231,268 Points

I gave a simple definition of hoisting above, click on the word for the MDN page. And here's a tutorial that explains it in greater detail: Understanding Hoisting in JavaScript.

In my second example, "a => a - 2" is an anonymous function expression using the compact modern form. You could substitute the classic form by writing it this way instead: "function (a) { return a - 2 }"