eyelidlessness eyelidlessness - 10 months ago 32
Javascript Question

Best javascript syntactic sugar

Here are some gems:


var obj = {}; // Object literal, equivalent to var obj = new Object();
var arr = []; // Array literal, equivalent to var arr = new Array();
var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something');


arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as:
arg = !!arg ? arg : 'default';

Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great:

(function() { ... })(); // Creates an anonymous function and executes it

Question: What other great syntactic sugar is available in javascript?


Getting the current datetime as milliseconds:

+new Date()

The unary + coerces the Date value to Number. The result is the same as either of these expressions:

Number(new Date())
new Date().getTime()

For example, to time the execution of a section of code:

var start = +new Date();
// some code
alert((+new Date() - start) + " ms elapsed");