Best javascript syntactic sugar

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?

13924 次浏览

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

Use === to compare value and type:

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


if (i == s)  // true


if (i === s) // false

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;

Being able to extend native JavaScript types via prototypal inheritance.

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

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.

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

Object membership test:

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


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

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).

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"

The Array#forEach on Javascript 1.6

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

I forgot:

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

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

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.

int to string cast

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

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

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

  var $$ = document.getElementById;


$$('samText');

Resize the Length of an Array

length property is a not read only. You can use it to increase or decrease the size of an array.

var myArray = [1,2,3];
myArray.length // 3 elements.
myArray.length = 2; //Deletes the last element.
myArray.length = 20 // Adds 18 elements to the array; the elements have the empty value. A sparse array.
element.innerHTML = "";  // Replaces body of HTML element with an empty string.

A shortcut to delete all child nodes of element.

JavaScript's Date class providing a semi-"Fluent Interface". This makes up for not being able to extract the date portion from a Date class directly:

var today = new Date((new Date()).setHours(0, 0, 0, 0));

It's not a fully Fluent Interface because the following will only give us a numerical value which is not actually a Date object:

var today = new Date().setHours(0, 0, 0, 0);

Default fallback:

var foo = {}; // empty object literal


alert(foo.bar) // will alert "undefined"


alert(foo.bar || "bar"); // will alert the fallback ("bar")

A practical example:

// will result in a type error
if (foo.bar.length === 0)


// with a default fallback you are always sure that the length
// property will be available.
if ((foo.bar || "").length === 0)

Like the default operator, || is the guard operator, &&.

answer = obj && obj.property

as opposed to

if (obj) {
answer = obj.property;
}
else {
answer = null;
}

Create an anonymous object literal with simply: ({})

Example: need to know if objects have the valueOf method:

var hasValueOf = !!({}).valueOf

Bonus syntactic sugar: the double-not '!!' for converting pretty much anything into a Boolean very succinctly.

In parsing situations with a fixed set of component parts:

var str = "John Doe";

You can assign the results directly into variables, using the "destructuring assignment" synatx:

var [fname, lname] = str.split(" ");
alert(lname + ", " + fname);

Which is a bit more readable than:

var a = str.split(" ");
alert(a[1] + ", " + a[0]);

Alternately:

var [str, fname, lname] = str.match(/(.*) (.*)/);

Note that this is a Javascript 1.7 feature. So that's Mozilla 2.0+ and Chrome 6+ browsers, at this time.

I love how simple it is to work with lists:

var numberName = ["zero", "one", "two", "three", "four"][number];

And hashes:

var numberValue = {"zero":0, "one":1, "two":2, "three":3, "four":4}[numberName];

In most other languages this would be quite heavy code. Value defaults are also lovely. For example error code reporting:

var errorDesc = {301: "Moved Permanently",
404: "Resource not found",
503: "Server down"
}[errorNo] || "An unknown error has occurred";

Here's one I just discovered: null check before calling function:

a = b && b.length;

This is a shorter equivalent to:

a = b ? b.length : null;

The best part is that you can check a property chain:

a = b && b.c && b.c.length;

Immediately Invoked Arrow function:

var test = "hello, world!";
(() => test)(); //returns "hello, world!";

Convert string to integer defaulting to 0 if imposible,

0 | "3" //result = 3
0 | "some string" -> //result = 0
0 | "0" -> 0 //result = 0

Can be useful in some cases, mostly when 0 is considered as bad result

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