📜 ⬆️ ⬇️

5 popular javascript hacks

There are several JavaScript hacks that are constantly used by experienced programmers. They are not completely obvious, especially for beginners. These hacks use language features that have some side effects. In this article I will explain how 5 such common hacks work.

Operator use !! to convert to boolean


Everything in JavaScript can be interpreted as true or false . This means that if you place an object in a conditional if , it will either execute a true code branch (when the object is true ), or execute a false branch (respectively, when the object has a false value).

0, false, "", null, undefined, NaN - these are false values. All other values ​​return true . Sometimes you may need to convert a variable to a boolean value. This can be done with the help of the operator !! :
')
 var something = 'variable'; !!something // returns true 


On the other hand, instead of if (x == "test") you can simply write if (x) . If x is an empty variable, then just the code from the else block will be executed.

Converting a string to a number using the + operator


In JavaScript + , this is a unary operator that returns a numeric representation of an operand or NaN if the operand does not have one. For example, using this operator, you can check whether the variable x number (such code can be seen in the underscore library): x === +x .

This method is not obvious. Most likely, you would use the parseFloat and parseInt methods.

Defining a default value with the operator ||


In javascript || is an example of the execution of a short circuit . This operator first analyzes the expression to its left, and, if it is false, analyzes the expression to the right. In any case, it returns the first true expression. Consider the following example:

 function setAge(age) { this.age = age || 10 } setAge(); 


In this example, we call the setAge() function setAge() no arguments, so age || 10 age || 10 returns 10 ( !!age == false ). This method is very good for setting variable values ​​by default. In fact, this approach is equivalent to the following example:

 var x; if (age) { this.age = age; } else { this.age = 10; } 


The first example with the operator || more concise, so this method is used throughout the world.

Personally, I often use this method. I like its conciseness and simplicity. However, it is worth noting that with this method you will not be able to set the variable to 0, since 0 is a false expression. Therefore, I advise using this method if necessary:

 this.age = (typeof age !== "undefined") ? age : 10; 


Use void 0 instead of undefined


The void keyword takes one argument and always returns undefined . Why not just use undefined ? Because in some browsers, undefined is just a variable that can be overridden. Therefore, void 0 gives us more confidence that nothing will be accidentally broken. Although you can find this hack in the source files of many libraries, I would not recommend using it regularly, since all ES5-compatible browsers do not allow overwriting the value of undefined .

Pattern encapsulation (function () {...}) ()


In ES5, there are only 2 types of scopes: global scope and function scope. Everything you write belongs to a global area that is accessible from anywhere in the code. It includes the declaration of variables and functions. However, what if you want to encapsulate most of the code, and leave only the interface in the global scope? Then you should use an anonymous function. Consider the following example:

 (function() { function div(a, b) { return a / b; } function divBy5(x) { return div(x, 5); } window.divBy5 = divBy5; })() div // => undefined divBy5(10); // => 2 


Of all the hacks listed in the article, this hack is the most harmless; You can and should use it in your projects to prevent the interaction of internal logic with the global scope.

In conclusion, I would like to remind you that any code you write should be simple and straightforward for other programmers. And any standard constructs provided by the language should be used first.

Some of the hacks discussed in the article can be solved more elegantly using ES6 (the next version of JavaScript). For example, in ES6 instead of age = age || 10 age = age || 10 you can write the following:

 function(age = 10) { // ... } 


Another example is the pattern (function() {...})() , which you are unlikely to use anymore after ES6 modules are supported by modern browsers.

Additional materials


If you want to dive into the subject of JS-hacks even deeper, the following resources may be useful to you:


Original article: javascript hacks explained
Article author: Yanis T

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


All Articles