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 trialRifqi Fahmi
23,164 PointsWhat is the benefit and drawback between function expression and declaration ??
I saw at stackoverflow that the different is function expression cannot be called before created, for example
showText(); // error
var showText = function() {
// do something
}
is that only the different ?? when we have to use function expression and why ? Thanks :D
1 Answer
Angelica Hart Lindh
19,465 PointsThis is expected behavior as you're assigning a function to a variable so it shouldn't be able to be called prior to its assignment. Another benefit of writing your functions as expressions is they are not 'hoisted' unlike function declarations. This allows for your function expression to retain local variables from the scope in which they were defined.
See below example:
var showText = function() {
var log = 'showText';
console.log(log);
};
showText();
// OR in ES2015 syntax
const showText2 = () => {
const log = 'showText2';
console.log(log);
};
showText2();
Rifqi Fahmi
23,164 PointsIn your jsfiddle file, theere is error that says Uncaught ReferenceError: log is not defined at line 5. Is it suppose to be error ?
Angelica Hart Lindh
19,465 PointsSorry, in the fiddle I had tried to reassign 'showText'. Updated and fixed now
f lsze
8,021 Pointswait .. shouldn't the closings be :
})();
I'm getting errors when running your examples (although curiously not in the fiddle.) Great answer though, totally helped me understand why you can't call a function expression before defining it!
Angelica Hart Lindh
19,465 PointsSure Filip you are correct, thanks for pointing that out, I'm not sure why they were working correctly in jsFiddle though.
I have updated the answer to remove the section about IIFE and updated the jsFiddle with an extra examples including passing parameters.
A X
12,842 PointsA X
12,842 PointsJust commenting that I too wondered this after watching this video.