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 trialAkash Sharma
Full Stack JavaScript Techdegree Student 14,147 PointsWhat is the difference between anonymous function and a variable statement with function expression?
For the below 2 functions, I do not understand Function B is not run immediately like Function A when the script is read.
Instead I have to call startTick(); it after the function B.
//Function A
(function () {
console.log("startTick");
clockSection.textContent = getTime();
})();
//Function B
var startTick = function () {
console.log("startTick");
clockSection.textContent = getTime();
};
2 Answers
Steven Parker
231,236 PointsThese are both anonymous function expressions, but the difference is what is being done with them. In the first case, it is being invoked which causes it to run, but it is not stored anywhere.
In the second case, it is being assigned, which saves it for later use but doesn't run it.
The second example is almost the same thing as a normal function definition:
var startTick = function () { ... } // this does almost exactly the same thing...
function startTick() { ... } // ...as this
The only difference I can think of is hoisting of normal definitions, which means they can be placed anywhere, but the assignments must occur before they are used.
Matt Brock
28,330 PointsFunction A is what's called an IIFE, or Immediately Invoked Function Expression. By wrapping the function operator and the entire expression in parenthesis, then adding the ()
immediately after, you are instructing the JavaScript interpreter to immediately run the code it just encountered. It's similar to what the pair of parenthesis does after any of function or method like .toUpperCase()
. Here's a great article on the subject: http://benalman.com/news/2010/11/immediately-invoked-function-expression/.