5

I've used JavaScript for a while and thought it would be useful (especially for those new to the language) to list some of my favorite shortcuts.

Ternary operator

Replace: if(a) then {b} else {c} With: (a) ? b:c;

Unary plus operator

Replace parseInt(x,10) + parseInt(y,10) with +x + +y

Array creation

Replace var ary = new Array(); with var ary = [];

Declaring variables

Replace var x; var y; var z = 3; with var x, y, z=3;

Multiline string (almost here-doc style)

Replace:

var str = 'this';
var str += 'covers';
var str += 'multiple';
var str += 'lines';

with:

var str = 'this \
covers \
multiple \
lines";

What others do you use?

Jose Blow
  • 67
  • 2
  • `var str += 'covers';` is invalid. The number conversion methods are definitely not equal, see [Comparison between all number-conversion methods](http://stackoverflow.com/a/8112802/938089?are-there-are-any-side-effects-of-using-this-method-to-convert-a-string-to-an-in). – Rob W Jan 26 '12 at 16:40
  • @PlatinumAzure I think that the OP means "Allow to write strings on multiple lines", since the suggested method does not include newlines either. – Rob W Jan 26 '12 at 16:42
  • Oops, quite right. I'll remove my other comment. – Platinum Azure Jan 26 '12 at 16:44
  • See the readme at https://github.com/mishoo/UglifyJS/ for some tricks. – biziclop Jan 26 '12 at 16:45

5 Answers5

5

To shorten the if condition blocks.

From:

var x;

if (a) {
    x = a;
} else if (b) {
    x = b;
} else {
    x = 100;
}

to:

x = a || b || 100;

You can use && to do the similar logic as well.

Grace Huang
  • 5,355
  • 5
  • 30
  • 52
2

Convert to string by adding empty string. Example:

var n = 1;
var s = 1 + '';
yas
  • 3,520
  • 4
  • 25
  • 38
0

Its not a question.

But you can use:

var a = {};

in place of:

var a = new Object();
Grace Huang
  • 5,355
  • 5
  • 30
  • 52
Jashwant
  • 28,410
  • 16
  • 70
  • 105
0

I think one of them will be object creation:

var obj = {}; instead of var obj = new Object();

emphaticsunshine
  • 3,725
  • 5
  • 32
  • 42
0

You can use list comprehension. Especially useful if you create a range method:

function range(n) {
  for (var i = 0; i < n; i++)
    yield i;
}

[2 * x for (x in range(100)) if (x * x > 3)]

in place of:

var myArray = []

for (x in range(100)){

    if (x * x > 3)
    {
        myArray.push(2*x);
    }

}

(Example taken from wikipedia)

RonnyKnoxville
  • 6,166
  • 10
  • 46
  • 75