Developers Club geek daily blog

1 year, 10 months ago
Shortcuts in JavaScript

Learning any programming language, it is useful to know about its features and to be able to use effectively language constructions. I want to share with you shortcuts for JS. These reductions in certain cases can facilitate reading a code, and also it is essential to reduce its quantity. However it is necessary to remember that they can play a dirty trick with you and if to use them everywhere, your code will stop being read and supported.

Use of while instead of for


Let's begin with the simple and rather often meeting council — to use while instead of for.

var count = foo.length
while (count--) {
// whatever
}
var count = foo.length
for(var i = 0; i < count; i++) {
// whatever
}

Of course, I like to use forEach and map, however too in cases when it is inappropriate, while looks more organically and readably. By the way, application of a variable for storage of length of an array is more productive, than calculation of this value in each iteration.

Use of for-in with normal arrays


Traditionally construction of for-in is used for iteration of objects, but it is worth to remember that it can use also for a normal array. And though in documentation it is specified that for-in does not guarantee consistency of search, in practice I did not meet a similar situation.

var count = foo.length
for(var i = 0; i < count; i++) {
// whatever foo[i]
}
for(var i in foo) {
// whatever foo[i]
}

Reduction to Boolean type


Sometimes it is required to lead value to Boolean type, and I will show a traditional solution of this task, and also its short form:

var foo = Boolean(bar); var foo = !!bar;

Double denial works as well as reduction, however it is fair to notice that, as well as in a case with all other shortcuts, beginners (and not only) can have difficulties in perception of such code.

Math.floor equivalent ();


There is very easy way to round any number to the next whole:

var intNum = Math.floor(anyNum); var intNum = ~~anyNum;

Double bit-by-bit denial works as Math.floor () for positive numbers and as Math.ceil () for negative. The explanation as it works, can be found here. It is more difficult to read, but saves ten characters.

Shortcuts for true and false


Even for true and false it is possible to make a shortcut. It looks already absolutely beyond the good and evil, but if we began this subject why and is not present:

var foo = true,
    bar = false;
var foo = !0,
    bar = !1;

But it is, whatever one may do, rather an anti-shortcut because it is absolutely unreadable, demands calculation from JS and in general looks discouragingly.

Conditional statement


For certain all are familiar with ternary operator, but not all know how convenient can be its use.

if (condition) {
  foo = bar;
} else {
  foo = baz;
}
foo = (condition ? bar : baz);

Already not bad, but it is possible to go further and to use it in several lines:

if (age > 18) {
  alert("OK, you can go.");
  location.assign("continue.html");
} else {
  location.assign("backToSchool.html");
}
age > 18 ? (
    alert("OK, you can go."),
    location.assign("continue.html")
) : (
    location.assign("backToSchool.html");
);

There is a small nuance: it is necessary to remember that operators in this case have to be separated by a comma, but not a semicolon. Other remarkable feature of this operator — he returns value (it was visible from the first example), so, it can be used also with functions.

if (condition) {
  function1();
} else {
  function2();
}
(condition ? function1 : function2)();

Use of AND


Not all remember how AND works — at first it calculates the first value and, only if it is equal to true, calculates another. Let's look how it can be applied.

if (foo) {
  bar();
}
if (foo) bar();
if (foo) bar();
foo &&bar();

Together with OR it is possible to achieve a complete equivalent of if-else, but it does not cost what your code will turn into.

Reduction of a line to number


var foo = parseFloat('3133.7'),
    bar = parseInt('31337');

The short form of this record is rather simple and elegant:

var foo = +'3133.7',
    bar = +'31337';

For the return task there is the shortcut too.

Reduction of number by the line


Here it is possible to show several examples as to make it:

var foo = 3.14,
    bar = foo.toString(10); // '3.14' 
var foo = 3.14,
    bar = foo + ''; // '3.14'
foo += ''; // '3.14'

I with an ulterior motive called the toString method with parameter 10 — he specifies that the number needs to be transformed to a line in decimal numeration. Respectively, for cases when you need to receive a line in hexadecimal number system, these shortcuts will not help.

Check of results of indexOf


Sometimes for verification of presence or lack of an element in an array write here such code:

if (someArray.indexOf(someElement) >= 0) {
// whatever
}

if (someArray.indexOf(someElement) === -1) {
// whatever
}

It can be reduced to it:

if (~someArray.indexOf(someElement)) {
// whatever
}

if (!~someArray.indexOf(someElement)) {
// whatever
}

To improve readability of this trick, check can be appropriated to a variable with the suitable name:

var isFound = ~someArray.indexOf(someElement);
if (isFound) {
// whatever
}

Converting of arguments in an array


For normal work with arguments in JS there are not enough tools therefore the requirement to transform arguments to a normal array arises often. And the first that will manage to be googled, will be

argsArray = Array.prototype.slice.call(arguments);

This challenge can be reduced to

argsArray = [].slice.call(arguments);

The array copy has an access to a prototype too that will save to us even 13 characters.

Check on null, undefined and empty


About this trick heard many, I will give it for those who did not know:

if (foo !== null || foo !== undefined || foo !== '') {
     bar = foo;
}
bar = foo || '';

Outputs


It would be desirable to pay attention once again that we reviewed these examples not to apply them everywhere, and only in order that it is better to understand possibilities of some constructions in JS.

This article is a translation of the original post at habrahabr.ru/post/273267/
If you have any questions regarding the material covered in the article above, please, contact the original author of the post.
If you have any complaints about this article or you want this article to be deleted, please, drop an email here: sysmagazine.com@gmail.com.

We believe that the knowledge, which is available at the most popular Russian IT blog habrahabr.ru, should be accessed by everyone, even though it is poorly translated.
Shared knowledge makes the world better.
Best wishes.

comments powered by Disqus