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!
I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...
Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices. While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...
I was incredibly happy when CSS text-overflow: ellipsis
(married with fixed width
and overflow: hidden
was introduced to the CSS spec and browsers; the feature allowed us to stop trying to marry JavaScript width calculation with string width calculation and truncation. CSS ellipsis was also very friendly to...
Before you send your user to an unknown external website, why not provide them a screenshot of the site via a tooltip so they may preview the upcoming page? Here's how you can do just that using MooTools.
The MooTools JavaScript
The first step is to grab...
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…