Wednesday, January 25, 2012

Neat JavaScript syntax shortcuts


Every language has a few nice features that are natural result of the syntax rules. It's just many really neat ones are not part of the mainstream code that is being written. Some examples:

Java's double brace initialization

final List<String> list = new ArrayList<String>() {{ 
    add("a");
    add("b");
    add("c");
}};

Ruby's idiomatic default assignment
my_data ||= ""

I came acorss a few nice JavaScript syntax "shortcuts" today that I haven't seen before. Maybe I just didn't pay attention?

Anonymous function call

If you write unobtrusive javascript or just unconsciously use a lot of jQuery then you do a lot of this:

(function($) {
...
})(jQuery);

well, if you're tired from wrapping all your anonymous functions into extra ( ) here's a shortcut for you:

!function($) {
...
}(jQuery);

Getting boolean out of virtually anything

Say you have something passed to your function or there's something you receive from another function and all you need to know is that it's "there". You basically need "true" if it exists or "false" otherwise. Here's a neat shortcut to do so:

myFlag = !!varToVerify;

The double negate will yield true for anything but a boolean false, NaN, or undefined (which will throw an error). Infinity will yield true. You can test it on jconsole:

!!parseInt('a'); // prints false
    a = !!1/0; // prints Infinity
    a ? 1 : 2; // prints 1
    !!b; // errors out with 'b' is not defined
    !!Object.prototype.toString; // prints true
    !!{}; // prints true

What else? what other neat JavaScript syntax "shortcuts" you can share?

4 comments:

DNNX said...

BTW, I saw bang-bang pattern in ruby code several times. See this link, for example http://stackoverflow.com/questions/524658/what-does-mean-in-ruby . So it's not purely "JavaScriptish" shortcut.

mzx said...

Java's double brace..
problem is that "list" is no more ArrayList but some hidden class that extends ArrayList with overriden methods with weird ClassName.

nice post

Unknown said...

A very nice shortcut for "get or assign if null":

var a = b || (b = new Class());

Pavel Veller said...

came across this nice post about "+" and "-" the other day: http://blog.caplin.com/2012/01/27/the-why-of-wat/