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

Adam Sawicki
Adam Sawicki
15,967 Points

function definition vs expression

Hi,

Can someone explain to me what are best practices using function definition and expression? I mean when use which one and basic concepts.

Best Regards, Adam Sawicki

Andrew Chalkley

2 Answers

Steven Parker
Steven Parker
231,007 Points

A function definition (also called a "function statement") exists as a complete statement, establishing a function with a specific name.

A function expression defines a function as a part of a larger expression syntax (typically a variable assignment or an argument passed to another function). Functions defined via expressions can be named or anonymous.

For more details, see these MDN pages on Function Statements and Function Expressions.

Adam Sawicki
Adam Sawicki
15,967 Points

Hi,

There are maybe guidelines/best practices where use which one ?

Best Regards, Adam

Steven Parker
Steven Parker
231,007 Points

Usually, where you use it will make the choice for you. If you're passing a callback function as an argument, you will naturally create a function expression. If you're just defining a function to be called later in the program, you'd generally use a function statement. And sometimes it doesn't matter:

// these do exactly the same thing:
function logit(n) { console.log(n); }        // function statement (perhaps easier to read)
var logit = function () { console.log(n); }; // assignment using function expression