📜 ⬆️ ⬇️

JavaScript Shortcuts



Studying any programming language, it is useful to know about its features and to be able to effectively use language constructs. I want to share with you shortcuts for JS. These abbreviations in some cases can facilitate reading the code, as well as significantly reduce its quantity. However, it should be remembered that they can play a cruel joke with you and, if you use them everywhere, your code will cease to be readable and supported.

Using while instead of for


Let's start with a simple and fairly common advice - 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 also like to use forEach and map, but in cases where it is inappropriate, while looks more organic and readable. By the way, using a variable to store the length of an array is more productive than calculating this value in each iteration.
')

Using for-in with regular arrays


Traditionally, for-in construction is used to iterate objects, but one should not forget that it can also be used for a regular array. And although the documentation states that for-in does not guarantee consistency of brute force, in practice I have not encountered 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] } 

Coercion to boolean type


Sometimes it is required to bring the value to a boolean type, and I will show the traditional solution of this problem, as well as its short form:

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

Double negation works in the same way as the cast, but it is fair to note that, as is the case with all the other shortcuts, newbies (and not only) may experience difficulties in perceiving such code.

Equivalent to Math.floor ();


There is a very simple way to round any number to the nearest integer:

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

Double bit negation works like Math.floor () for positive numbers and Math.ceil () for negative numbers. An explanation of how this works can be found here . Read more difficult, but saves ten characters.

Shortcuts for true and false


Even for true and false you can make shortcuts. It already looks beyond good and evil, but since we started this topic, then why not:

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

But this, whatever one may say, is rather an anti-shortcut, because it is completely unreadable, it requires computation on the part of JS, and in general it looks discouraging.

Conditional operator


Surely everyone is familiar with the ternary operator , but not everyone knows how convenient its use can be.

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

Already not bad, but you can go further and 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 must be remembered that the operators in this case should be separated by a comma, not a semicolon. Another remarkable feature of this operator is that it returns a value (this was evident from the first example), which means that it can also be used with functions.

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

Using AND


Not everyone remembers how AND works; first, it calculates the first value and, only if it is true, it calculates another. Let's see how this can be applied.

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

Together with OR, you can achieve the full equivalent of an if-else, but this is not worth what your code turns into.

Reduction of a string to a number


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

The short form of this entry is quite simple and elegant:

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

For the inverse problem, there is also a shortcut.

Casting number to string


Here you can demonstrate a few examples of how to do this:

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

I called the toString method with the parameter 10 for a reason - it indicates that the number should be converted to a string in the decimal number system. Accordingly, for cases when you need to get a string in hexadecimal number system, these shortcuts will not help.

Check indexOf results


Sometimes, to check the presence or absence of an element in an array, they write the following code:

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

It can be reduced to this:

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

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

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

Convert arguments to an array


There is not enough toolkit for normal work with arguments in JS, so the need to convert arguments to a regular array often arises. And the first thing that manages to google will be

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

This call can be reduced to

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

After all, an instance of the array also has access to the prototype, which will save us as much as 13 characters.

Check for null, undefined and empty


Many have heard about this trick, I will give it for those who did not know:

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

findings


I would like to pay attention once again that we considered these examples not in order to apply them everywhere, but only in order to better understand the capabilities of some constructions in JS.

Source: https://habr.com/ru/post/273267/


All Articles