Best javascript syntactic sugar

Viewed 13837

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?

31 Answers

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;
}

Use === to compare value and type:

var i = 0;
var s = "0";

if (i == s)  // true

if (i === s) // false

Multi-line strings:

var str = "This is \
all one \
string.";

Since you cannot indent the subsequent lines without also adding the whitespace into the string, people generally prefer to concatenate with the plus operator. But this does provide a nice here document capability.

Repeating a string such as "-" a specific number of times by leveraging the join method on an empty array:

var s = new Array(repeat+1).join("-");

Results in "---" when repeat == 3.

var tags = {
    name: "Jack",
    location: "USA"
};

"Name: {name}<br>From {location}".replace(/\{(.*?)\}/gim, function(all, match){
    return tags[match];
});

callback for string replace is just useful.

Getters and setters:

function Foo(bar)
{
    this._bar = bar;
}

Foo.prototype =
{
    get bar()
    {
        return this._bar;
    },

    set bar(bar)
    {
        this._bar = bar.toUpperCase();
    }
};

Gives us:

>>> var myFoo = new Foo("bar");
>>> myFoo.bar
"BAR"
>>> myFoo.bar = "Baz";
>>> myFoo.bar
"BAZ"

This isn't a javascript exclusive, but saves like three lines of code:

check ? value1 : value2

A little bit more on levik's example:

var foo = (condition) ? value1 : value2;

The Array#forEach on Javascript 1.6

myArray.forEach(function(element) { alert(element); });

Following obj || {default:true} syntax :

calling your function with this : hello(neededOne && neededTwo && needThree) if one parameter is undefined or false then it will call hello(false), sometimes usefull

I forgot:

(function() { ... }).someMethod(); // Functions as objects

I love being able to eval() a json string and get back a fully populated data structure. I Hate having to write everything at least twice (once for IE, again for Mozilla).

Assigining the frequently used keywords (or any methods) to the simple variables like ths

  var $$ = document.getElementById;

  $$('samText');

int to string cast

var i = 12;
var s = i+"";

Template literals

var a = 10;
var b = 20;
var text = `${a} + ${b} = ${a+b}`;

then the text variable will be like below!

10 + 20 = 30

optional chaining (?.) can be used so instead of:

if(error && error.response && error.response.msg){ // do something}

we can:

if(error?.response?.msg){ // do something }

more about optional chaining here

Related