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!
The <canvas>
element has been a revelation for the visual experts among our ranks. Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead. Here are nine unbelievable canvas demos that...
Kids these days, I tell ya. All they care about is the technology. The video games. The bottled water. Oh, and the texting, always the texting. Back in my day, all we had was...OK, I had all of these things too. But I still don't get...
Both of the two great browser vendors, Google and Mozilla, have Extensions pages that utilize simple but classy animation effects to enhance the page. One of the extensions used by Google is a basic margin-top animation to switch between two panes: a graphic pane...
One of my favorite uses of the MooTools JavaScript library is the SmoothScroll plugin. I use it on my website, my employer's website, and on many customer websites. The best part about the plugin is that it's so easy to implement.
I recently ran...
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…