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!
![Create a Sheen Logo Effect with CSS]()
I was inspired when I first saw Addy Osmani's original ShineTime blog post. The hover sheen effect is simple but awesome. When I started my blog redesign, I really wanted to use a sheen effect with my logo. Using two HTML elements and...
![Write Better JavaScript with Promises]()
You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...
![Drag and Drop MooTools File Uploads]()
Honesty hour confession: file uploading within the web browser sucks. It just does. Like the ugly SELECT element, the file input is almost unstylable and looks different on different platforms. Add to those criticism the fact that we're all used to drag and drop operations...
![Create Tiny URLs with TinyURL, MooTools, and PHP]()
Since we've already figured out how to create TinyURL URLs remotely using PHP, we may as well create a small AJAX-enabled tiny URL creator. Using MooTools to do so is almost too easy.
The XHTML (Form)
We need an input box where the user will enter...
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…