Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best javascript syntactic sugar

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

Object membership test:

var props = { a: 1, b: 2 };

("a" in props) // true
("b" in props) // true
("c" in props) // false

In Mozilla (and reportedly IE7) you can create an XML constant using:

var xml = <elem></elem>;

You can substitute variables as well:

var elem = "html";
var text = "Some text";
var xml = <{elem}>{text}</{elem}>;

Using anonymous functions and a closure to create a private variable (information hiding) and the associated get/set methods:

var getter, setter;

(function()
{
   var _privateVar=123;
   getter = function() { return _privateVar; };
   setter = function(v) { _privateVar = v; };
})()

Being able to extend native JavaScript types via prototypal inheritance.

String.prototype.isNullOrEmpty = function(input) {
    return input === null || input.length === 0;
}