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 trialRyan Atkins
8,635 PointsClosures?
I am working with Angular following a beginner tutorial series and ran into closures. I can't recall learning them or hearing the term. I did so reading and got a mild grasp on them but I still don't understand this:
(function () {
var app = angular.module('teamPopulate', []);
app.controller('teamPopController', function () {
this.team = team;
});
var team = {
name: "Columbus Crew SC",
city: "Columbus",
state: "Ohio",
color: "yellow"
};
// Why do I add these parentheses to the back of this? It won't work without them and I don't get it
})();
Commented what I didn't get.
1 Answer
Andrew Kiernan
26,892 PointsHi Ryan!
This pattern is known as an immediately invoked function expression (or IIFE). The parenthesis at the end are invoking the preceding function. Without those, you will have declared your function but haven't invoked it, so it won't run.
Think of it like any regular function. If you were to write out your function:
function addTwo(number) {
console.log(number + 2);
}
your function is declared, but it doesn't actually do anything until you invoke it:
addTwo(3); // Logs out 5
An IIFE works the same way, you are declaring your function and then running it immediately with those parenthesis on the end.
I hope that helps! Let me know if you have any questions.
-Andrew
Ryan Atkins
8,635 PointsRyan Atkins
8,635 PointsSo it does those two examples in one swipe, but as an anonymous function?
Andrew Kiernan
26,892 PointsAndrew Kiernan
26,892 PointsYep! Using my example as an anonymous function would be:
You can even name the function and it works the same way, plus gives you the added benefit of a function name to find in error messages.