Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some popular JavaScript shortcuts/tricks? [closed]

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?

like image 711
Jose Blow Avatar asked Jan 26 '12 16:01

Jose Blow


2 Answers

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.

like image 123
Grace Shao Avatar answered Sep 22 '22 15:09

Grace Shao


Convert to string by adding empty string. Example:

var n = 1;
var s = 1 + '';
like image 36
yas Avatar answered Sep 22 '22 15:09

yas