5 popular JavaScript hacks

There are several JavaScript hacks that experienced programmers use constantly. They are not entirely obvious, especially for beginners. These hacks take advantage of language features that have some side effects. In this article, I will explain how 5 of these common hacks work.

Using an operator !!to convert to a boolean value

Everything in JavaScript can be interpreted as true or false . This means that if you place the object in a conditional statement if, it will either trueexecute a code highlight (when the object has a value true) or perform a falsecolor highlight (respectively, when the object has a value false).

0, false, "", null, undefined, NaN are false values. All other values ​​return true. Sometimes you may need to convert a variable to a boolean value. This can be done using the operator !!:

var something = 'variable';
!!something // returns true

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

Convert strings to numbers using the + operator

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

This method is not obvious. Most likely, you would apply the parseFloatand  methods parseInt.

Defining a default value with the || operator

JavaScript ||is an example of performing a short circuit . This operator first parses the expression to its left, and if it is false, parses 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 

In this example, we call the function setAge()with no arguments, thus age || 10returning 10 ( !!age == false). This method is very good for setting default values ​​for variables. 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 an operator is ||more concise, which is why this method is used all over 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 you to use this method if necessary:

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

Using void 0 instead of undefined

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

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

In ES5, there are only 2 types of scope: the global scope and the scope of a function. 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 understandable to other programmers. And any standard constructs provided by the language should be used first.

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

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

Another example is a pattern (function() {...})()that you are unlikely to use after ES6 modules are supported by modern browsers.

Additional materials

If you want to dive deeper into the topic of JS hacks , the following resources may come in handy:

Original article: JavaScript hacks explained
Author of the article: Yanis T

Also popular now: