Immediately Executing Functions
JavaScript is full of nifty little tricks to accomplish tasks with less code. One of those tricks is immediately executing functions. We oftentimes see this pattern for executing anonymous functions to limit variable scope:
(function() {
console.log('executed!');
// Do processing here
})();
What many developers don't know is that this code can be shorted by using a ! before the anonymous function:
!function() {
console.log('executed!');
// Do processing here
}()
The function above executes immediately, just as the first snippet did. One caveat: the immediately executing function always returns false. If you desire the result of the anonymous function, you wont want to use this second pattern.
Ben Alman has created an excellent, detailed writeup on the subject and if you want to learn more, be sure to visit his post!
David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...
My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...
Developers everywhere seem to be looking for different ways to make use of JavaScript libraries. Some creations are extremely practical, others aren't. This one may be more on the "aren't" side but used correctly, my TextOverlap plugin could add another interesting design element...
This article serves as a first step toward mastering SVG element animation. Included within are links to key resources for diving deeper, so bookmark this page and refer back to it throughout your journey toward SVG mastery.
An SVG element is a special type of DOM element...
Because not quite enough people pulled out their hair on encountering the function(){…}() syntax.
The first is not exactly valid. The right call has the call-parentheses inside the container parentheses.
I think the ! is works with call-parentheses too. So it’s not shorter.
I think such oddities should be removed from the language.
What would ever be the argument for doing this? A Obfuscated Javascript Code Contest?
Why even use such a function? I don’t get it. If you want code to execute immediatly, just write it outside a ‘function’. What’s the point of an anonymous function you can’t call later on for reusability? Or am I missing something?
Encapsulation of vars…