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 trialOly Su
6,119 PointsWhat are the pro's and con's of using Function Statement v.s. Function Expression?
Hi all,
At the team I'm working at our standard practice is using Function Statements.
Would anyone kindly share the benefit of either choices?
One benefit I can think of is, I assume Function Expression stores it in the browser's memory, which is not as performant as using Function Statement?
Many thanks :)
1 Answer
Dave McFarland
Treehouse TeacherHi Oly Su
First let's make sure we're talking about the same thing. A function declaration (also sometimes called a function statement) looks like this:
function myFunction() {
}
A function expression looks like this:
var myFunction = function () {
};
The main difference between the two is that a function declaration can be placed ANYWHERE in a script including at the bottom of the script. The browser's JavaScript interpreter reads the script before running anything and commits the function to memory. Because of this it can be called anywhere in the script -- even BEFORE the declaration actually appears in the script. For example, this works:
sayHi();
function sayHi() {
alert('Hi');
};
A function expression, on the other hand, is only created during runtime -- in other words you can't call the function until the JavaScript interpreter evaluates (or runs) the expression. For example this WON'T work:
sayHi(); // produces an "undefined is not a function" error
var sayHi = function() {
alert('Hi');
};
To avoid all this confusion, it's often a good idea to declare your functions at the beginning of a script when possible.
I do not believe there is any (or at least any significant) performance boost for using a function expression,
Oly Su
6,119 PointsOly Su
6,119 PointsMany thanks for your thorough answer, this really helps :)