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>() {{ 

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($) {

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

!function($) {

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?


DNNX said...

BTW, I saw bang-bang pattern in ruby code several times. See this link, for example . 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

Alexander Yezutov 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: