Best javascript syntactic sugar

eyelidlessness picture eyelidlessness · Oct 8, 2008 · Viewed 12.9k times · Source

Here are some gems:

Literals:

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');

Defaults:

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?

Answer

Chris Noe picture Chris Noe · Oct 22, 2008

Getting the current datetime as milliseconds:

Date.now()

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

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