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!
![Conquering Impostor Syndrome]()
Two years ago I documented my struggles with Imposter Syndrome and the response was immense. I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions. I've even caught myself reading the post...
![Create a CSS Flipping Animation]()
CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...
![MooTools-Like Element Creation in jQuery]()
I really dislike jQuery's element creation syntax. It's basically the same as typing out HTML but within a JavaScript string...ugly! Luckily Basil Goldman has created a jQuery plugin that allows you to create elements using MooTools-like syntax.
Standard jQuery Element Creation
Looks exactly like writing out...
![Dijit’s TabContainer Layout: Easy Tabbed Content]()
One of Dojo's major advantages over other JavaScript toolkits is its Dijit library. Dijit is a UI framework comprised of JavaScript widget classes, CSS files, and HTML templates. One very useful layout class is the TabContainer. TabContainer allows you to quickly create a tabbed content...
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…